我正在尝试解决一个场景,其中父级将包含一个模块,并且当单击父级内部的按钮时,将出现模块。
现在,模块中将会有一个关闭按钮,单击该按钮将隐藏该模块。下次单击父按钮时,模块应该再次出现,依此类推。
到目前为止的代码:
var Parent = React.createClass({
getInitialState(){
return{
showModule: false
};
},
render(){
return(
<div className="parent" onClick={this._showModule}>
Click me to show module
<Module show={this.state.showModule}/>
</div>
);
},
_showModule(){
this.setState({
showModule: true
});
}
});
var Module = React.createClass({
getInitialState(){
return{
show: this.props.show
};
},
componentWillReceiveProps(nextProps){
console.log('componentWillReceiveProps is called');
this.setState({
show: nextProps.show
});
},
render(){
return(
(this.state.show?
<div className="module" onClick={this._hide}>
Click me and I will disappear myself
</div> : null
)
);
},
_hide(){
this.setState({
show: false
});
}
});
这里的问题是,每当我调用 Module 中的 hide 函数(通过将 state.show 更改为 false 来隐藏自身)时,componentWillReceiveProps 就会被调用。
难道不应该只在 Parent 传递新的 props 时才调用它吗?子模块调用 componentWillReceiveProps 时的状态如何以及为何发生变化?
最佳答案
当您单击“单击我,我会消失”时,您实际上单击了 Parent 并调用了 Parent._showModule 处理程序。 改变
<div className="parent" onClick={this._showModule}>
Click me to show module
<Module show={this.state.showModule}/>
</div>
至
<div className="parent">
<p onClick={this._showModule}>Click me to show module</p>
<Module show={this.state.showModule}/>
</div>
关于javascript - ReactJS:在状态更改时调用 componentWillReceiveProps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31502145/