【发布时间】: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