wrapperComponentRef未定义-React Ant Design,表单组件

时间:2019-01-05 22:21:46

标签: javascript reactjs ant-design-pro

我正在使用Ant设计-具有React的Form和Modal组件。

表单包装器组件:

class InsertForm extends React.Component{
    render(){
        const formItemLayout = {
            labelCol: { span: 24 },
            wrapperCol: { span: 24},
        };
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <Form.Item
                    {...formItemLayout}
                    label="Title"
                >
                    {getFieldDecorator('title', {

                    })(
                        <Input placeholder="Title" />
                    )}
                 </Form.Item>
......
            </div>
        )
    }
}
const InsertFormWrapper = Form.create()(InsertForm);

我正在Modal内的同一文件的另一个组件中调用此组件(这就是为什么我不导出表单组件),并且我正在使用wrappedComponentRef

export default class InsertCont extends React.Component{
    constructor(props){
        super(props);
        console.log(this.form) // Undefined
    }
    insert = () => {
            console.log(this.form); // Not undefined
        }
    render(){
        <Modal
            ...{modalProps}
            onOk={this.insert}
        >
            <InsertFormWrapper
                wrappedComponentRef={(form) => this.form = form}
            />
        </Modal>
    }
}

问题在于,在构造函数中,引用this.form是未定义的,但是如果已打开模式并单击确定按钮-onOk={this.insert},则引用不是未定义的。

2 个答案:

答案 0 :(得分:1)

顺便说一句,我还没有完全研究您的问题或代码,但是我遇到了同样的问题并已解决,所以我想我知道出了什么问题。

您不能将带有包装的组件传递到其他组件中。我认为这必须是自己的路线(在BrowserRouter中)。

这个问题在包装器组件中...在这里->

const InsertFormWrapper = Form.create()(InsertForm);

然后在InsertCont组件的渲染中使用它...在这里->

render() {
        <InsertFormWrapper
            wrappedComponentRef={(form) => this.form = form}
        />
    </Modal>
}

您有几种解决方法

  • 删除包装器,找到实现所需内容的另一种方法
  • 以某种方式使组件具有自己的路线
  • 将整个组件放在容器中

明智地选择;)

答案 1 :(得分:0)

在构造函数中未定义的原因是,当您到达构造函数时,您的代码仅定义了InsertCont,但尚未调用render(),这就是wrappedComponentRef的位置设置this.form

请参阅The React Lifecycle: Mounting以了解为什么会这样。创建任何React组件时,这是调用函数的顺序:

  1. constructor()
  2. static getDerivedStateFromProps()
  3. render()
  4. componentDidMount()