reactjs - 如何使用 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
解决方案
此答案适用于 antd 版本 3。
您需要用 包装您的组件Form.create
,然后该form
对象将被注入到您的组件的道具中。
事后参考一下:
function FormDrawerButton(props) {
...
const { getFieldDecorator } = props.form;
return (
<>
...
</>
);
}
export default Form.create()(FormDrawerButton);
这是我的其他答案中功能组件中表单的代码沙箱示例:
推荐阅读
- arrays - 为什么excel中的vlookup返回NA或不匹配?
- mysql - 在 WHERE 子句中无法识别具有替换的子查询
- reactjs - 浏览器后退按钮上未调用 useEffect 清理
- ssh - FIWARE 规则设置远程连接
- python - 我不明白为什么我收到错误“IndexError:字符串索引超出范围”
- python - 如何从列中获取属性高度、宽度、x 和 y?
- java - 如何用匹配子字符串长度的一个字符替换字符串模式?
- html - 不使用 CSS 浮动复制 html 定位
- javascript - 如何制作密码认证程序
- omnet++ - 在 OMNeT++ 中使用 INET 进行仿真时出错