我正在尝试了解子组件如何更改其父组件的状态,并意识到我能够成功完成此操作的唯一示例(也是我在网上看到的唯一示例)处理从 child 的 parent ,然后链接到 child 中的事件(onClick、onChange 等)。因此,如果子组件使用事件调用继承的回调,子组件是否只能更改其父组件的状态?
这个有效:
class Child extends React.Component{
handleClick(){
console.log('pressed')
this.props.message('Hi mom!')
}
render(){
return (<button onClick={this.handleClick.bind(this)}>Prese Me</button>)
}
};
class Parent extends React.Component {
constructor(props){
super(props)
this.state = {
messageFromChild: '',
}
this.callBackFromParent = this.callBackFromParent.bind(this);
}
callBackFromParent(dataFromChild){
this.setState({messageFromChild: dataFromChild})
}
render(){
return (
<div>
<h2>Message from Child is:</h2>
<h2>{this.state.messageFromChild}</h2>
<Child message={this.callBackFromParent}/>
</div>
)
}
}
但这会导致无限循环:
class Child extends React.Component{
render(){
this.props.message('Hi Mom')
return(
<h2>Dummy message from child</h2>
)
}
};
class Parent extends React.Component {
constructor(props){
super(props)
this.state = {
messageFromChild: '',
}
this.callBackFromParent = this.callBackFromParent.bind(this);
}
callBackFromParent(dataFromChild){
this.setState({messageFromChild: dataFromChild})
}
render(){
return (
<div>
<h2>Message from Child is:</h2>
<h2>{this.state.messageFromChild}</h2>
<Child message={this.callBackFromParent}/>
</div>
)
}
}
最佳答案
您不一定需要将函数用作事件处理程序,但直接在 render 上调用它会导致父组件立即 setState
,这将导致 的另一个渲染子
组件,循环继续。你可以例如在 Child
的 componentDidMount
中设置超时,它将正常工作。
关于javascript - 如果事件被触发,子组件只能改变父状态吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51338381/