11

我正在尝试重现https://github.com/ant-design/ant-design/blob/master/components/form/demo/horizo ​​ntal-login.md 中的 antd Form 示例

用 extends React.Component 替换 React.createClass 但我得到一个 Uncaught TypeError: Cannot read property 'getFieldDecorator' of undefined

使用以下代码:

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>
        )
    }
}

看起来缺少 Form.create 部分是导致问题的原因,但不知道它适合使用扩展机制的位置。

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

4

3 回答 3

18

@vladimirimp 是在正确的轨道上,但选择的答案有 2 个问题。

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

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

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

export default Form.create()(HorizontalLoginForm);

那么我们就可以HorizontalLoginForm直接使用了,不需要设置新的变量。(但如果你确实将它设置为一个新变量,你会想要命名该变量MyHorizontalLoginForm或以大写字母开头的任何其他内容)。

于 2018-01-30T20:34:38.623 回答
2

当您希望将表单类包含在父组件中时,您必须首先创建表单,例如在父组件的渲染方法中:

    ...

    render() {
        ...

        const myHorizontalLoginForm = Form.create()(HorizontalLoginForm);
        ...
          return (
          ...
          <myHorizontalLoginForm />
          )
    }

请务必在父类中导入您的 Horizo​​ntalLoginForm 类。

于 2016-12-16T14:14:25.903 回答
2

可以学习官方例子:https ://ant.design/components/form/#components-form-demo-advanced-search

Form.create@vladimirp 调用渲染不好。

于 2016-12-27T01:56:39.313 回答