ReactJS:在状态改变时调用componentWillReceiveProps?
问题描述:
我试图解决一个情况,其中家长将包括一个模块,当一个按钮被点击内部父母,模块将出现。ReactJS:在状态改变时调用componentWillReceiveProps?
现在,模块中会出现一个关闭按钮,单击它可以隐藏模块。下次点击父按钮,模块应该再次出现,依此类推。到目前为止
代码:
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
});
}
});
这里的问题是,每当我调用模块的隐藏功能(它通过改变state.show为false来隐藏自身),componentWillReceiveProps被调用。
只有当父母传递新道具时,它不应该被调用吗?子模块调用componentWillReceiveProps时如何以及为什么会改变状态?
答
当你点击“点击我,我会自己消失,”你竟然点击父叫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>
很好的解释! –