【发布时间】:2018-12-22 14:49:11
【问题描述】:
我试图了解子组件如何更改其父组件的状态,并意识到我能够成功完成此操作的唯一示例(以及我在网上看到的唯一示例)处理从孩子的父母,然后链接到孩子中的事件(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>
)
}
}
【问题讨论】:
-
您不一定需要将函数用作事件处理程序,但直接在渲染时调用它会导致父组件立即
setState,这将导致Child的另一个渲染组件,然后循环继续。你可以例如在Child的componentDidMount中设置超时,它会正常工作。
标签: javascript reactjs react-native jsx