【问题标题】:Calling a function to change state in parent component from the child component in react调用函数以从反应中的子组件更改父组件中的状态
【发布时间】:2026-02-18 08:50:01
【问题描述】:

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

父组件的状态为:

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

【问题讨论】:

  • 请提供更多代码
  • 尝试将this.setState 作为道具传递给您的孩子。

标签: reactjs


【解决方案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>
        )
    }
});

【讨论】:

  • 我现在不在电脑前,但我一回来就试试这个。但是在这种情况下,我需要在 Child 元素中调用 changeHandler 对吗?所以应该是this.props.changeHandler而不是this.props.handleChange()
  • 刚刚测试过,父组件的状态仍然没有改变
  • @ogk 哎呀感谢您发现我的错误。是的,你应该叫this.props.changeHandler
最近更新 更多