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

Mar*_*edo 11 reactjs antd

我试图在https://github.com/ant-design/ant-design/blob/master/components/form/demo/horizo​​ntal-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', {
            rules: [{ required: true, 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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我该怎么做呢?

Luk*_*uke 15

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

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

要解决这个问题,我们只需更改默认导出HorizontalLoginForm:

class HorizontalLoginForm extends React.Component { /* ... */ }

export default Form.create()(HorizontalLoginForm);
Run Code Online (Sandbox Code Playgroud)

然后我们可以HorizontalLoginForm直接使用而无需将其设置为新变量.(但如果你确实将它设置为一个新变量,你可能想要命名该变量MyHorizontalLoginForm或以大写字母开头的任何其他内容).