wrappedComponentRef未定义 - React Ant Design,Form Component

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

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

javascript reactjs ant-design-pro
1个回答
1
投票

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

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

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

1
投票

顺便说一下,我没有完全看你的问题或代码,但我遇到了同样的问题并解决了它,所以我想我知道什么是错的。

您无法将包装器的组件传递到其他组件中。我认为它必须是它自己的路线(在BrowserRouter)。

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

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

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

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

你有几个解决方案

  • 删除包装器并找到另一种方法来实现您的需要
  • 以某种方式使组件成为自己的路线
  • 破坏垃圾箱中的整个组件

做出明智的选择 ;)

© www.soinside.com 2019 - 2024. All rights reserved.