- 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()
- }
-
- }