代码之家  ›  专栏  ›  技术社区  ›  Suhail Gupta

无法读取未定义的属性“getFieldDecorator”,因为我试图在组件中使用antd的表单

  •  0
  • Suhail Gupta  · 技术社区  · 7 年前

    我想用antd的 form 用打字稿。我不确定我做错了什么。当我尝试渲染组件时,会出现一个错误,错误是:

    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;
    

    上述组件将从另一个组件导出并渲染。我犯这个错误的原因是什么?

    1 回复  |  直到 7 年前
        1
  •  4
  •   sathish kumar    7 年前

    你需要用Antd表单包装你的组件。创建()如下所示:

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