![](/img/trans.png)
[英]React Ant design Uncaught TypeError: Cannot read property 'Component' of undefined
[英]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组件时,这是调用函数的顺序:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
顺便说一句,我还没有完全研究您的问题或代码,但是我遇到了同样的问题并已解决,所以我想我知道出了什么问题。
您不能将带有包装的组件传递给其他组件。 我认为它必须是自己的路由(在BrowserRouter
)。
这意味着问题出在包装器组件中...在这里->
const InsertFormWrapper = Form.create()(InsertForm);
然后在InsertCont
组件的渲染中使用它...这里->
render() {
<InsertFormWrapper
wrappedComponentRef={(form) => this.form = form}
/>
</Modal>
}
您有几个解决方案
做出明智的选择 ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.