首页 文章

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

提问于
浏览
1

我正在使用props来改变父组件的状态 .

父组件的状态是:

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 回答

  • 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>
            )
        }
    });
    

相关问题