当我尝试在组件中使用antd的表单时,无法读取未定义的属性'getFieldDecorator'

问题描述 投票:0回答:1

我正在尝试使用antd的form与打字稿。我不确定我做错了什么。当我尝试渲染组件时,我得到一个错误说:

TypeError: Cannot read property 'getFieldDecorator' of undefined

这发生在render方法的第一行:

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个回答
1
投票

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

CleaningLimitPolicy = Form.create(name : "yourFormName")(CleaningLimitPolicy)
export default CleaningLimitPolicy;
© www.soinside.com 2019 - 2024. All rights reserved.