例如,我们有一个组件(这是一个孩子):
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
。但是在这种情况下,这些都没有帮助。我还考虑过用新的道具重新渲染子组件,但是我不能从父组件重新渲染它。
知道我们如何用子状态进行操作吗?
如果要更改父级组件中的模态状态,则应在那里(在父级组件上)对其进行处理。在Child
这种情况下可以是无状态的部件,其从父调用的功能。有没有理由不这样做呢?
例如:
<Button onClick={props.open}>Open</Button>
<Modal show={props.show} onHide={props.close}>
.........
<Button onClick={props.close}>Close</Button>
</Modal>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句