首页 > 解决方案 > 如何使用 getFieldDecorator 和 react (function) hooks

问题描述

我正在尝试创建一个简单的 antd 表单,但不知道如何使 getFieldDecorator 与我的 react 函数一起使用。我如何翻译this.props.form成反应钩子方法?这是来自 antd 文档的类语法。

  function FormDrawerButton () {

  // ToggleDrawer
  const [visible, setVisible] = useState(false);

  const toggleDrawer = () => {
    setVisible(!visible)
  }

const { getFieldDecorator } = this.props.form; // how to use this?

  return (
    <>
    <Button
      type="primary"
      icon="edit"
      size="large"
      style={{ float: 'right' }}
      onClick={ toggleDrawer }
    >
      Add user
    </Button>
  <div>
    <Drawer
      title="Create a new user"
      width={720}
      onClose={ toggleDrawer }
      visible={ visible }
    >
    <p>Form</p>
    <Form className="login-form">
        <Form.Item>
          {getFieldDecorator('username', {
            rules: [{ required: true, message: 'Please input your username!' }],
          })(
            <Input
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="Username"
            />,
          )}
        </Form.Item>
    </Form>
    </Drawer>
  </div>
  </>
  )
}

export default FormDrawerButton

标签: reactjsformsreact-hooksantd

解决方案


此答案适用于 antd 版本 3。

您需要用 包装您的组件Form.create,然后该form对象将被注入到您的组件的道具中。

事后参考一下:

function FormDrawerButton(props) {
  ...

  const { getFieldDecorator } = props.form;

  return (
    <>
      ...
    </>
  );
}

export default Form.create()(FormDrawerButton);

这是我的其他答案中功能组件中表单的代码沙箱示例:

编辑 Q-58289639-FormFieldValidate


推荐阅读