function App(){
const cntEl:any = React.useRef(null); // I don't know what type should be here.
React.useEffect(()=>{
if(cntEl.current){ cuntEl.current.start() }
}, []);
return <Countdown ref={cntEl} />
}
const Countdown = React.forwardRef((props,ref) => {
React.useImperativeHandle(ref, ()=>({
start() {
alert('Start');
}
});
return <div>Countdown</div>
});
我尝试使用ref
和React.useImperativeHandle()
在父组件中使用子方法。
效果很好。
但是由于const cntEl:any
,我不满意。
我相信有很多方法可以避免使用我不知道的any
类型。
我只需要可以替换的类型any
。
已编辑
当我将鼠标悬停在(property) React.MutableRefObject<null>.current: null
时可以看到cntEl.current
无需将cntEl
键入为any
。另外,您可以将Countdown用作useRef
const cntEl = React.useRef<Countdown>(null);
尝试:
const ref1 = useRef<HTMLElement>(null!);
const ref2 = useRef<HTMLElement | null>(null);
[使用
useRef
时,创建没有初始值的引用容器时,有两个选择:第一个选项将使
ref1.current
只读,并打算传递到React将管理的内置ref属性中(因为React会为您设置当前值)。第二个选项将使
ref2.current
mutable,并用于您自己管理的“实例变量”。