调用一个函数来改变父组件中的状态,从子组件中做出反应

时间:2016-01-04 09:13:10

标签: reactjs

我使用道具来改变父组件的状态。

父组件的状态是:

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,因为我可以控制从其中记录状态。但是,状态永远不会变为虚假。有谁知道我在这里犯了什么错误?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望在单击按钮时切换父组件的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>
        )
    }
});
相关问题