Ant Design Drawer 抽屉关闭后怎么清除表单数据?

百里米阳 阅读 3

我在用 Ant Design 的 Drawer 组件做侧边弹窗,里面放了个 Form 表单。现在问题是:每次打开抽屉都会保留上次填写的内容,即使我手动点了关闭按钮。我试过在 onClose 里调用 form.resetFields(),但有时候会报错说 form 还没初始化。

有没有稳妥的办法在抽屉关闭时清空表单?或者是不是应该在 visible 变成 false 的时候处理?下面是我的部分代码:

const MyDrawer = () => {
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();

  const onClose = () => {
    form.resetFields(); // 有时这里报错
    setVisible(false);
  };

  return (
    <Drawer visible={visible} onClose={onClose}>
      <Form form={form}>
        <Form.Item name="username">
          <Input />
        </Form.Item>
      </Form>
    </Drawer>
  );
};
我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
IT人小菊
用 useEffect 监听 visible 状态,关闭时重置表单,比在 onClose 里处理稳妥得多:

useEffect(() => {
if (!visible) {
form.resetFields();
}
}, [visible]);


把这段放在组件里,visible 变成 false 时自动清空表单,不会出现 form 未初始化的报错。
点赞
2026-03-12 18:05