簡體   English   中英

從子組件中調用函數以更改父組件中的狀態

[英]Calling a function to change state in parent component from the child component in react

我正在使用道具來更改父組件的狀態。

父組件的狀態為:

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函數只是將open的狀態設置為:

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

現在正在調用handleChange,因為我可以從中控制台記錄狀態。 但是,狀態永遠不會切換為false。 有人知道我在這里犯了什么錯誤嗎?

如果我理解正確,那么您想在單擊按鈕時切換父組件的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>
        )
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM