【发布时间】:2015-06-14 05:15:11
【问题描述】:
我有一个相当简单的问题,我不确定如何使用 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>
而且我知道如何关闭模式,但不能同时关闭。不确定如何保持父子模式共享和可控的状态。
更新
为了尽可能保持模块化,我认为 React 的方式是将打开/关闭逻辑存储在 modal 变量中。
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: how to modify child state or props from parent?
【问题讨论】: