2016-01-04 61 views
1

我正在使用道具來更改父組件的狀態。調用函數來改變父組件中父狀態的狀態

父組件的狀態是:

getInitialState: function() { 
    return { 
    open: false 
    } 
} 

父組件渲染:

//the state of the button is currently false but when a user presses it the state is set to true 
<button whichState={this.handleChange} onClick={this.setStateToTrue}> 

然後,當用戶做一些動作的子組件觸發一個呼叫在功能父組件。

子組件:

//User does some action that calls a function that calls whichState 
callWhichState: function() { 
    this.props.whichState(); 
} 

回到我的父組件handleChange功能只是設置的開放狀態:

handleChange: function() { 
    this.setState({  
    open: false 
    }); 
} 

眼下handleChange被稱爲我我通過道具做到這一點可以控制檯從其中記錄狀態。但是,狀態從不切換到假。有誰知道我在這裏犯了什麼錯誤?

+0

請提供更多代碼 – FranBran

+0

嘗試將'this.setState'作爲道具傳遞給您的孩子。 – Noitidart

回答

1

如果我理解正確,您希望在單擊按鈕時切換父組件的open狀態?

var Parent = React.createClass({ 
    getInitialState: function(){ 
     return { 
      open: false 
     } 
    } 
    handleChange: function(){ 
     this.setState({open: !this.state.open}); 
    } 
    render: function(){ 
     return (
      <Child changeHandler={this.handleChange}></Child> 
     ) 
    } 
}); 

var Child = React.createClass({ 
    handleChange: function(){ 
     this.props.changeHandler(); 
    } 
    render: function(){ 
     return (
      <button onClick={this.handleChange}></button> 
     ) 
    } 
}); 
+0

我現在不在我的電腦,但我會盡快嘗試。然而在這種情況下,我需要在Child元素中調用changeHandler嗎?所以,而不是'this.props.handleChange()'它應該是'this.props.changeHandler' – ogk

+0

只是測試它,並且狀態仍然永遠不會改變在父組件 – ogk

+0

@ogk oops感謝您捕捉我的錯誤。是的,你應該叫'this.props.changeHandler' – Carpetfizz

相關問題