2015-07-19 62 views
1

我試圖解決一個情況,其中家長將包括一個模塊,當一個按鈕被點擊內部父母,模塊將出現。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時如何以及爲什麼會改變狀態?

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

回答

3

當你點擊「點擊我,我會自己消失,」你竟然點擊父叫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

+0

很好的解釋! –

相關問題