ReactJS:在状态更改时调用componentWillReceiveProps?

时间:2015-07-19 14:16:56

标签: javascript reactjs react-jsx

我试图解决一个场景,其中父级将包含一个模块,当在父级内部单击一个按钮时,将出现模块。

现在,模块中会有一个关闭按钮,点击它会隐藏模块。下次单击父按钮时,模块应再次出现,依此类推。

到目前为止

代码:

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

只有在父母传递新道具时才能调用它?如何以及为什么在子模块中调用状态更改会调用componentWillReceiveProps?

JsBin http://jsbin.com/cunuci/edit?js,console,output

1 个答案:

答案 0 :(得分:3)

当你点击&#34;点击我,我将自己消失&#34;你实际上点击了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>

http://jsbin.com/naloxafile/1/edit?js,console,output