天天看點

react元件通信子元件擷取父元件

這裡寫目錄标題

  • 子元件擷取父元件
    • 父元件擷取子元件
    • 類元件中父元件擷取子元件

子元件擷取父元件

可通過props接收

父元件擷取子元件

useRef将ref綁定到某個子元件标簽上,用以擷取整個子元件的方法和參數

useImperativeHandle: 可以自定義暴露給父元件的方法或者變量

父元件

import React, { useState, useRef } from 'react'
import ChildList from './ChildList'

export default () => {
    let parentRef = useRef(null)
    const [name, setName] = useState('li')
    return <div>
        <ChildList parentRef={parentRef} name={name}></ChildList>
        <button onClick={() => {
            console.log("parentRef", parentRef)
        }}>擷取子元件</button>
    </div>
}
           

子元件

import React, { useImperativeHandle, forwardRef } from 'react'

export default forwardRef((props) => {
    console.log("props", props)
    const { parentRef } = props;
    useImperativeHandle(parentRef, () => {
        return {
            childFn
        }
    })
    console.log(parentRef)
    const childFn = () => {
        console.log('子元件方法')
    }
    return <div>
        <div ref={parentRef} />
    </div>
})
           

類元件中父元件擷取子元件

當在子元件中調用onRef函數時,正在調用從父元件傳遞的函數。this.props.onRef(this)這裡的參數指向子元件本身,父元件接收該引用作為第一個參數:onRef = {ref =>(this.child = ref)}然後它使用this.child儲存引用。之後,可以在父元件内通路整個子元件執行個體,并且可以調用子元件函數。

// 父元件
class Parent extends React.Component {
  handleClick=()=>{
    this.child.handleChildClick() // -> 通過this.child可以拿到child所有狀态和方法
  }
  render() {
    return <div>
      <ChildList onRef={(ref) => {this.child = ref}} />
      <button onClick={this.handleClick}>父元件按鈕</button>
    </div>
  }
}

           
// 子元件
class ChildList extends React.Component {
  constructor(props) {
    super(props)
  }
  componentDidMount(){
    this.props.onRef(this)// ->将child自己傳遞給this.props.onRef()方法
  }
  handleChildClick=()=>{
    console.log('通過父元件按鈕擷取到子元件資訊啦啦啦')
  } 
  render(){
    return <div>我是子元件</div>
  }
}