我有一个具有布尔状态属性“ showModal”的父组件。当showModal为true时,我呈现子组件“ Modal”。该模式具有关闭按钮,该按钮应将“ showModal”属性切换回false。“ showModal”作为prop传递给子Modal组件,但是由于prop在React中是不可变的,因此我还没有找到更改它的正确模式。
我可以使用某种双向数据绑定吗?处理此问题的最佳方法是什么?
这是您的操作方法。这是JSBin的工作示例:https ://jsbin.com/yixano/2/edit ? html,js,output
var ModalParent = React.createClass({
getInitialState: function() {
return {showModal: false};
},
toggleShowModal: function() {
this.setState({showModal: !this.state.showModal});
},
render: function() {
return (
<div>
<button type="button" onClick={this.toggleShowModal.bind(this)}>Toggle Show Modal</button>
{this.state.showModal ?
<Modal onModalClose={this.toggleShowModal.bind(this)}/> :
<div></div>}
<h4>State is: </h4>
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</div>);
}
});
var Modal = React.createClass({
render: function(){
return <div><button type="buton" onClick={this.props.onModalClose}>Close</button></div>
}
});
ReactDOM.render(<ModalParent/>, document.getElementById("app"));
这里的想法是将对ModalParent上的函数的引用传递给Modal,以便可以根据子级中的操作来更改父级中的状态。
如您所见,该子项有一个名为“ onModalClose”的道具,它需要一个函数引用,该函数引用是在单击关闭按钮时被调用的。在父级中,我们将相应的toggleShowModal绑定到此onModalClose属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句