reactjs – 使用扩展的React.Component机制正确创建一个antd表单

前端之家收集整理的这篇文章主要介绍了reactjs – 使用扩展的React.Component机制正确创建一个antd表单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在 https://github.com/ant-design/ant-design/blob/master/components/form/demo/horizontal-login.md中重现antd Form示例

用扩展React.Component替换React.createClass但是我得到一个Uncaught TypeError:无法读取未定义的属性’getFieldDecorator’

使用以下代码

  1. import { Form,Icon,Input,Button } from 'antd';
  2. const FormItem = Form.Item;
  3.  
  4. export default class HorizontalLoginForm extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. }
  8.  
  9. handleSubmit(e) {
  10. e.preventDefault();
  11. this.props.form.validateFields((err,values) => {
  12. if (!err) {
  13. console.log('Received values of form: ',values);
  14. }
  15. });
  16. },render() {
  17. const { getFieldDecorator } = this.props.form;
  18. return (
  19. <Form inline onSubmit={this.handleSubmit}>
  20. <FormItem>
  21. {getFieldDecorator('userName',{
  22. rules: [{ required: true,message: 'Please input your username!' }],})(
  23. <Input addonBefore={<Icon type="user" />} placeholder="Username" />
  24. )}
  25. </FormItem>
  26. <FormItem>
  27. {getFieldDecorator('password',message: 'Please input your Password!' }],})(
  28. <Input addonBefore={<Icon type="lock" />} type="password" placeholder="Password" />
  29. )}
  30. </FormItem>
  31. <FormItem>
  32. <Button type="primary" htmlType="submit">Log in</Button>
  33. </FormItem>
  34. </Form>
  35. )
  36. }
  37. }

看起来缺少Form.create部分导致问题,但不知道它使用扩展机制适合哪里.

我怎么能正确地做到这一点?

@vladimirimp走在正确的轨道上,但所选答案有2个问题.

>不应在render方法调用高阶组件(如Form.create()).
> JSX要求用户定义的组件名称(例如myHorizo​​ntalLoginForm)以大写字母开头.

解决这个问题,我们只需要更改Horizo​​ntalLoginForm的默认导出:

  1. class HorizontalLoginForm extends React.Component { /* ... */ }
  2.  
  3. export default Form.create()(HorizontalLoginForm);

然后我们可以直接使用Horizo​​ntalLoginForm而无需将其设置为新变量. (但如果您确实将其设置为新变量,则需要将该变量命名为MyHorizo​​ntalLoginForm或以大写字母开头的任何其他内容).

猜你在找的React相关文章