本文主要是介绍forwardRef, useImperativeHandle实现父组件调用子组件方法(个人笔记,非教程),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import React, { memo, forwardRef,useRef, useImperativeHandle, type ForwardRefExoticComponent, type PropsWithoutRef, type RefAttributes } from 'react'interface Props{组件属性(不需要声明ref属性类型)
}export interface ForwardRefProps{fn:()=> void
}// 子组件
const Child:ForwardRefExoticComponent<PropsWithoutRef<Props> & RefAttributes<ForwardRefProps>> = memo(forwardRef<ForwardRefProps, Props>((props, ref) => {useImperativeHandle(ref, () => {return {fn() {console.log('fn')}}})}// 父组件
function Parent(){const ref = useRef<ForwardRefProps>()function test(){ref.current.fn()}}
这篇关于forwardRef, useImperativeHandle实现父组件调用子组件方法(个人笔记,非教程)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!