类组件:
父组件通过ref可以调用子组件的方法。
函数组件:
就要做些处理 主要是useImperativeHandle 把需要的函数暴露给父组件。forwardRef可以用,也可以不用。
不带forwardRef
//父组件
import React, { memo, ReactNode, useEffect, useRef } from 'react'
import type { FC } from 'react'
import Child from './Children'
interface Iprops {
children?: ReactNode
}
const Parent: FC<Iprops> = () => {
const curref: any = useRef()
useEffect(() => {
curref.current?.fn('ref:父组件调用子组件函数')
}, [curref])
return <Child onRef={curref} />
}
export default memo(Parent)
//子组件
import React, { FC, memo, ReactNode, useImperativeHandle } from 'react'
interface Iprops {
onRef: any
children?: ReactNode
}
const Child: FC<Iprops> = ({ onRef }) => {
const fn = (val) => {
console.log(val)
}
useImperativeHandle(onRef, () => {
return {
fn: fn
}
})
return (
<div>
<button>按钮</button>
</div>
)
}
export default memo(Child)
带forwardRef
//父组件
import React, { memo, ReactNode, useEffect, useRef } from 'react'
import type { FC } from 'react'
import Child from './Children'
interface Iprops {
children?: ReactNode
}
const Parent: FC<Iprops> = () => {
const curref: any = useRef()
useEffect(() => {
curref.current?.fn('ref:父组件调用子组件函数')
}, [curref])
return <Child ref={curref} />
}
export default memo(Parent)
//子组件
import React, {
FC,
forwardRef,
memo,
ReactNode,
useImperativeHandle
} from 'react'
interface Iprops {
onRef: any
children?: ReactNode
}
const Child = (props: Iprops, ref) => {
const fn = (val) => {
console.log(val)
}
useImperativeHandle(ref, () => {
return {
fn: fn
}
})
return (
<div>
<button>按钮</button>
</div>
)
}
export default memo(forwardRef(Child))
个人比较喜欢第一中全部放在props里面,写法简单,没有forwardRef繁琐。