转自:https://blog.csdn.net/yesyoucan_/article/details/82531779
react 子组件更新父组件状态
class Father extends Component {
construtor(props){
super(props);
this.state={
name: 'Peter',
age: '26'
}
}
onChangeState(stateName){
this.setState(stateName)
}
render(){
<p>姓名:{this.state.name}</p>
<p>年龄:{this.state.age}</p>
<Child onClicked={this.onChangeState.bind(this)}/>
}
}
class Child extends Component {
render(){
<Button onClicked={()=>this.props.onClicked({name: 'John'})}/>
}
}
解析:
在父组件添加事件同名属性赋值一个回调函数,
子组件触发事件,
回调函数调用this.setState()修改父组件状态。
例子中的回调函数,如果用ES6的语法来写比较简介,可以不用使用bind专门绑定this