wrappedComponentRef 是未定义的 - React Ant Design, Form Component



我正在使用 Ant design - Form and Modal 组件和 React。

表单包装器组件:

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是未定义的,但如果模式打开并单击 OK 按钮 - onOk={this.insert} ref 不是未定义的。

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

请参考 反应生命周期:挂载 看看为什么会这样。 创建任何 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>
}

您有几个解决方案

  • 删除包装器并找到另一种实现所需内容的方法
  • 以某种方式使组件成为自己的路由
  • 在箱中破折整个组件

明智地选择;)

最新更新