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

53 阅读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: getData,
        otherFun: otherFun
    }))
    function getData() {
        // to do something
    }
    function otherFun() {
        console.log('这是其他方法')
    }
    return (
        <div>子组件</div>
    )
})

此时,在父组件中就可以随心所欲的调用子组件中的方法了!
也可以获取子组件定义的ref


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