繁体   English   中英

wrapperComponentRef未定义-React Ant Design,Form Component

[英]wrappedComponentRef is undefined - React Ant Design, Form Component

我正在使用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>
    }
}

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

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

请参阅《 React生命周期:安装》以了解为什么会这样。 创建任何React组件时,这是调用函数的顺序:

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

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

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

这意味着问题出在包装器组件中...在这里->

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

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

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

您有几个解决方案

  • 删除包装,找到实现您所需要的其他方法
  • 使组件以某种方式成为自己的路线
  • 将整个组件冲破

做出明智的选择 ;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM