【发布时间】:2016-04-02 21:51:28
【问题描述】:
例如,我们有一个组件(这是一个子组件):
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {show: props.show || false};
this.close = this.close.bind(this);
this.open = this.open.bind(this);
}
close() {
this.setState({show: false});
}
open() {
this.setState({show: true});
}
render() {
return (
<div>
<Button onClick={this.open}>Open</Button>
<Modal show={this.state.show} onHide={this.close}>
.........
<Button onClick={this.close}>Close</Button>
</Modal>
</div>
);
}
}
我们有父组件:
class Parents extends React.Component {
constructor(props) {
super(props);
this.state = {show: false};
this.open = this.open.bind(this);
}
open() {
this.setState({show: true});
}
render() {
return (
<div>
<Button onClick={this.open}>open</Button>
<Child show={this.state.show}/>
</div>
)
}
}
所以我只想能够从父母那里打开模态元素,然后能够从孩子那里改变相同的孩子状态。
我尝试使用 componentWillReceiveProps() 并且我使用 npm 包:react-komposer。但在这种情况下,这些都没有帮助。
我也想过用新的道具重新渲染子组件,但我不能从父组件重新渲染它。
知道如何使用子状态进行操作吗?
【问题讨论】:
-
检查dis..stackoverflow.com/questions/36026781/…你想要一样吗?
-
其实不一样
标签: javascript reactjs