hooks父元件怎麼呼叫子元件的方法?

小白张先生發表於2024-05-09

父元件使用 useRef 建立一個 ref 傳入 子元件; 子元件需要使用useImperativeHandle 暴露 ref 自定義的例項值給父元件。這個需要用 forwardRef 包裹著。
父元件
const ref = useRef()
ref.current & ref.current.init()

子元件
const previewImgModal: React.FC<{ ref: any }> = forwardRef(({ }, ref) => {
useImperativeHandle(ref, () => ({
init: init,
}));
}))

相關文章