React 函数式组件之父组件调用子组件的方法

427 阅读1分钟

第一步:

在父组件中,使用 useRef 创建一个 ref

import { useRef } from 'react'
// 父组件中代码
const FCom = () => {
    const cRef = useRef(null);
    return (
        <div>
            <ChildCom ref={cRef} />
        </div>
    )
    
}

第二步:

子组件中代码:(使用了 forwardRef,useImperativeHandle)

import { forwardRef, useImperativeHandle } from 'react'
const ChildCom = forwardRef(({
  // 这里是一些props参数
}, ref) => {
    useImperativeHandle(ref, () => ({
        getData
    }))
    const getData = () => {
        // to do something
    }
    return (
        <div>子组件</div>
    )
})

第三步:

此时,在父组件中就可以调用子组件中的方法了!

import { useRef } from 'react'
// 修改父组件中代码
const FCom = () => {
    const cRef = useRef(null);
    const handleClick = () => {
        if(cRef.current){
            cRef.current.getData()
        }
    }
    return (
        <div>
            <ChildCom ref={cRef} />
        </div>
    )
    
}