react ref 用法案例(支持ts提示)
// 子组件 import React, { useEffect, useImperativeHandle } from "react";
export interface DynamicFormRef {
xxxx:()=>void;
}
const Index = (props: ChooseDocumentProps, ref: React.MutableRefObject<DynamicFormRef> ) => {
// ... const [ { showModal, }, setState, ] = useImmer<ChooseDocumentState>({ showModal: false }); // ...
const xxxx = ()=>{
} useImperativeHandle(ref, () => ({ setVisible(status:boolean) { setState(st => { st.showModal = status; }) },
xxxx })); // ... } export default React.forwardRef(Index);
// 父组件调用子组件 // ... const ChooseDocumentRef = useRef<DynamicFormRef>();
// ... ChooseDocumentRef?.current?.setVisible(true); // ... <ChooseDocument ref={ChooseDocumentRef}/>
参考:Hooks 的 useImperativeHandle 怎么用? - 简书 (jianshu.com)