我有一个相当简单的问题,我不确定如何使用 React 的单向数据流来解决它。
假设您在父级中有一个显示模态的链接
在模态中,您有一个“X”来关闭它。
我知道我可以通过 props 从父级更改模态的状态
// In the parent
<Modal display={this.state.showModal} />
// In the modal
<div className={this.props.display ? "show" : "hide"}>
<a className="close">×</a>
...
</div>
我知道如何关闭模态,但不能同时关闭。不确定如何保持由父模态和子模态共享和控制的状态。
更新
为了尽可能保持module化,我认为 React 的方式是将打开/关闭逻辑存储在模态变量中。
var ParentThing = React.createClass({
...
render (
<Modal /> // How can I call this.open in the modal from here?
)
});
var Modal = React.createClass({
setInitialState: function() {
return {
display: false
}
},
close: function() {
this.setState({ display: false });
},
open: function() {
this.setState({ display: true });
},
render: function() {
return (
<div className={this.state.display ? "show" : "hide"}>
<a className="close" onClick={this.close}>×</a>
</div>
)
}
});
我看到了这个方法,但似乎比我在这里需要做的要多一些。Reactjs:如何从父级修改子状态或props?