React-組件間通信之onRef方法(refs轉發)


組件間通信除了props外還有onRef方法,不過React官方文檔建議不要過度依賴ref。本文使用onRef語境為在表單錄入時提取公共組件,在提交時分別獲取表單信息。

下面demo中點擊父組件按鈕可以獲取子組件全部信息,包括狀態和方法,可以看下demo中控制台打印。

// 父組件
class Parent extends React.Component {
  testRef=(ref)=>{
    this.child = ref
    console.log(ref) // -> 獲取整個Child元素
  }
  handleClick=()=>{
    alert(this.child.state.info) // -> 通過this.child可以拿到child所有狀態和方法
  }
  render() {
    return <div>
      <Child onRef={this.testRef} />
      <button onClick={this.handleClick}>父組件按鈕</button>
    </div>
  }
}
// 子組件
class Child extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      info:'快點擊子組件按鈕哈哈哈'
    }
  }
  componentDidMount(){
    this.props.onRef(this)
    console.log(this) // ->將child傳遞給this.props.onRef()方法
  }
  handleChildClick=()=>{
    this.setState({info:'通過父組件按鈕獲取到子組件信息啦啦啦'})
  } 
  render(){
    return <button onClick={this.handleChildClick}>子組件按鈕</button>
  }
}

原理:

當在子組件中調用onRef函數時,正在調用從父組件傳遞的函數。this.props.onRef(this)這里的參數指向子組件本身,父組件接收該引用作為第一個參數:onRef = {ref =>(this.child = ref)}然后它使用this.child保存引用。之后,可以在父組件內訪問整個子組件實例,並且可以調用子組件函數。

react官方文檔refs轉發


免責聲明!

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



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