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()

原文鏈接:點我跳轉或者點我跳轉


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM