reactjs – 使用扩展的React.Component机制正确创建一个antd表单
发布时间:2020-12-15 20:44:57 所属栏目:百科 来源:网络整理
导读:我试图在 https://github.com/ant-design/ant-design/blob/master/components/form/demo/horizontal-login.md中重现antd Form示例 用扩展React.Component替换React.createClass但是我得到一个Uncaught TypeError:无法读取未定义的属性’getFieldDecorator’
我试图在
https://github.com/ant-design/ant-design/blob/master/components/form/demo/horizontal-login.md中重现antd Form示例
用扩展React.Component替换React.createClass但是我得到一个Uncaught TypeError:无法读取未定义的属性’getFieldDecorator’ 使用以下代码: import { Form,Icon,Input,Button } from 'antd'; const FormItem = Form.Item; export default class HorizontalLoginForm extends React.Component { constructor(props) { super(props); } handleSubmit(e) { e.preventDefault(); this.props.form.validateFields((err,values) => { if (!err) { console.log('Received values of form: ',values); } }); },render() { const { getFieldDecorator } = this.props.form; return ( <Form inline onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('userName',{ rules: [{ required: true,message: 'Please input your username!' }],})( <Input addonBefore={<Icon type="user" />} placeholder="Username" /> )} </FormItem> <FormItem> {getFieldDecorator('password',message: 'Please input your Password!' }],})( <Input addonBefore={<Icon type="lock" />} type="password" placeholder="Password" /> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit">Log in</Button> </FormItem> </Form> ) } } 看起来缺少Form.create部分导致问题,但不知道它使用扩展机制适合哪里. 我怎么能正确地做到这一点?
@vladimirimp走在正确的轨道上,但所选答案有2个问题.
>不应在render方法中调用高阶组件(如Form.create()). 要解决这个问题,我们只需要更改Horizo??ntalLoginForm的默认导出: class HorizontalLoginForm extends React.Component { /* ... */ } export default Form.create()(HorizontalLoginForm); 然后我们可以直接使用Horizo??ntalLoginForm而无需将其设置为新变量. (但如果您确实将其设置为新变量,则需要将该变量命名为MyHorizo??ntalLoginForm或以大写字母开头的任何其他内容). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |