Javascript React props={this.refs.something}未定义

Javascript React props={this.refs.something}未定义,javascript,reactjs,Javascript,Reactjs,我的应用程序中有一个组件 Modal有两种方法,分别是show()和hide(),我在其中更改组件的状态 在我的应用程序中,我有: <App> <Modal ref="modal"/> <Menu openModal={this.refs.modal.show}/> </App> 但是在菜单中,this.props.openModal未定义 有人能解释一下原因吗?可能是因为在渲染时,this.refs.modal尚未定义 您应该做

我的应用程序中有一个
组件

Modal有两种方法,分别是
show()
hide()
,我在其中更改组件的状态

在我的应用程序中,我有:

<App>
   <Modal ref="modal"/>
   <Menu openModal={this.refs.modal.show}/>
</App>

但是在菜单
中,this.props.openModal
未定义


有人能解释一下原因吗?

可能是因为在渲染时,this.refs.modal尚未定义

您应该做的是在应用程序组件上设置一些状态,然后回调以更改该状态,该状态将作为道具传递给模态

getInitialState: function() {
    return {modalOpen: false};
},
setModalOpen: function(open) {
    this.setState({modalOpen: false});
}
...
render: function () {
    return (
        <App>
            <Modal open={this.state.modalOpen} setOpen={this.setModalOpen}/>
            <Menu openModal={this.setModalOpen}/>
        </App>
    );
}
getInitialState:function(){
返回{modalOpen:false};
},
setModalOpen:功能(打开){
this.setState({modalOpen:false});
}
...
渲染:函数(){
返回(
);
}

然后,您可以将模态的状态作为一个道具来读取,但还要注意,模态组件应该使用回调来设置应用程序组件的状态,并且只使用该道具,而不是使用它自己的内部状态来覆盖它。

这可能是因为在渲染时,还没有定义this.refs.modal

您应该做的是在应用程序组件上设置一些状态,然后回调以更改该状态,该状态将作为道具传递给模态

getInitialState: function() {
    return {modalOpen: false};
},
setModalOpen: function(open) {
    this.setState({modalOpen: false});
}
...
render: function () {
    return (
        <App>
            <Modal open={this.state.modalOpen} setOpen={this.setModalOpen}/>
            <Menu openModal={this.setModalOpen}/>
        </App>
    );
}
getInitialState:function(){
返回{modalOpen:false};
},
setModalOpen:功能(打开){
this.setState({modalOpen:false});
}
...
渲染:函数(){
返回(
);
}

然后,您可以将模态的状态作为一个道具来读取,但还要注意模态组件应该使用回调来设置应用程序组件的状态,并且只使用该道具,而不是使用它自己的内部状态来覆盖它。

不是答案,但我建议您使用模态上的道具来显示或隐藏它。在大多数情况下,使用refs是反模式的,尤其是对于这种命令式调用。因此,在OpenModel上,您将状态更改为{show:true},然后将show={this.state.show}传递给Modal。我不确定您是否有打字错误,而不是
this.refs.Modal.show
应该是
this.refs.Modal
在菜单中我有一个元素,我想在其中触发模态打开,我如何才能正确实现这一点?@the,show是modal类的方法,在这里我没有打开答案,但我建议您使用modal上的道具来显示或隐藏它。在大多数情况下,使用refs是反模式的,尤其是对于这种命令式调用。因此,在OpenModel上,您将状态更改为{show:true},然后将show={this.state.show}传递给Modal。我不确定您是否有打字错误,而不是
this.refs.Modal.show
应该是
this.refs.Modal
在菜单中我有一个元素,我想在其中触发模态打开,我如何才能正确实现这一点?@the,show是modal类的方法,我在这里打开