【问题标题】:Cannot read property 'getFieldDecorator' of undefined as I try to use antd's form within a component当我尝试在组件中使用 antd 的表单时,无法读取未定义的属性“getFieldDecorator”
【发布时间】:2019-03-14 11:45:08
【问题描述】:

我正在尝试将 antd 的 form 与 typescript 一起使用。我不确定我做错了什么。当我尝试渲染组件时,我收到一条错误消息:

TypeError: Cannot read property 'getFieldDecorator' of undefined

这发生在渲染方法的第一行:

const { getFieldDecorator } = this.props.form;

为什么form 未使用组件的this.props 定义?我试图通读,但无法得到这个错误的确切原因。

   import React from "react";
   import { Button, Input, message, Form, Radio } from "antd";
   import { FormComponentProps } from "antd/lib/form/Form";
   import { withWideContainer, withHeader } from "client/components/WithContainer";

    const FormItem = Form.Item;


    type state = {};

    type props = {};

    class CleaningLimitPolicies extends React.Component<
    FormComponentProps & props,
    state
    > {
        constructor(props) {
            super(props);

            this.state = {};
        }

        afterValid() {}

        render() {

            // FOLLOWING LINE THROWS THE ERROR

            const { getFieldDecorator } = this.props.form;

            const view = (
            <div className="d-flex align-items-start">
                <Form onSubmit={this.afterValid}>
                <FormItem label="Use Microbial Limits?">
                    {getFieldDecorator("use_microbial_limits", {
                    rules: [
                        {
                        required: true,
                        message: "Please fill out this field"
                        }
                    ],
                    initialValue: true
                    })(
                    <Radio.Group>
                        <Radio value={true}>Yes</Radio>
                        <Radio value={false}>No</Radio>
                    </Radio.Group>
                    )}
                </FormItem>
                <Button
                    type="primary"
                    htmlType="submit"
                    style={{ display: "none" }}
                />
                </Form>
            </div>
            );

            return withWideContainer(view);
        }
    }

    const CleaningLimitPolicy = withHeader(
        CleaningLimitPolicies,
        "Policy",
        true
    );

    export default CleaningLimitPolicy;

上面的组件是从另一个组件导出和渲染的。我收到此错误的原因可能是什么?

【问题讨论】:

    标签: javascript reactjs typescript antd


    【解决方案1】:

    你需要使用 Antd Form.create() 来包装你的组件,如下所示:

    CleaningLimitPolicy = Form.create(name : "yourFormName")(CleaningLimitPolicy)
    export default CleaningLimitPolicy;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 2013-10-01
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多