react如何在子组件中改变父组件的state

主要作用:可以在子组件中刷新父组件,或者想从子组件传值到父组件

//父组件
class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.updateParent= this.updateParent.bind(this);
  }

  updateParent(someValue:any) {
    console.log(someValue);//在这里就可以取到子组件传来的值
    this.setState({
      someState: someValue
    })
  }

  render() {
    return <Child updateParent= {this.updateParent} />
  }
}

//子组件
class Child extends React.Component {
  render() {
    return <Button onClick = {this.props.updateParent(someValue)}/ >
  }
}

子组件可以像例子中这样直接绑定事件触发,或者在其他方法中调用this.props.updateParent()

原文链接:点我跳转或者点我跳转

原文地址:https://www.cnblogs.com/li-you/p/7656028.html