useRef 与 useImperativeHandle 的组合使用

84 阅读1分钟

在项目重构中,为了获取子组件的实例,并且方便得进行调取,将公共部分抽取成插件形式,使用React编码。 父组件:

const Index = (props) => { return ( <Pay ref={payRef}/> ) }

子组件:

const Pay = forwradRef((props: PayProps, ref: any)) => { confirm = () => { .... } useImperativeHandle(res, () => ({ comfirm: confirm, })) useState(() => { }, []); return <div></div> })

父组件调用子组件的方法: ` interface PayRefType { confirm: () => void; } const payRef = useRef(); const confirm = () => { payRef.current?.confirm(); }

return ( <> </> ) `