【问题标题】:How to use the getFieldDecorator with react (function) hooks如何使用 getFieldDecorator 和 react (function) hooks
【发布时间】:2020-02-07 16:19:54
【问题描述】:

我正在尝试创建一个简单的 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

【问题讨论】:

标签: reactjs forms react-hooks antd


【解决方案1】:

此答案适用于 antd 版本 3。

你需要用Form.create包裹你的组件,然后form对象会被注入到你组件的props中。

以后再参考一下:

function FormDrawerButton(props) {
  ...

  const { getFieldDecorator } = props.form;

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

export default Form.create()(FormDrawerButton);

这是功能组件from my other answer中表单的代码沙箱示例:

【讨论】:

  • 目前,这失败了 _antd.Form.create(...) is not a function
  • @MariusB 版本 3,版本 4 有新的 API,我在沙箱中更新了 antd 版本
  • 谢谢,但似乎 v4.0 标签 forceRender 已损坏,因此我无法升级....
【解决方案2】:

如果使用类组件则使用const { getFieldDecorator } = this.props.form; 如果使用功能组件,则使用const { getFieldDecorator } = props.form;

因为(this.)用于对象引用,类内组件需要引用,但功能组件不需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2020-11-08
    • 2019-08-16
    • 1970-01-01
    相关资源
    最近更新 更多