React props={this.refs.something} undefined

React props={this.refs.something} undefined

本文关键字:something undefined refs this props React      更新时间:2024-05-05

我的APP中有一个<Modal/>组件。

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

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

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

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

有人能解释一下原因吗?

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

您应该做的是在应用程序组件上设置一些状态,然后回调以更改该状态,并将其作为道具传递给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>
    );
}

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