使用React.useImperativeHandle()声明类型

问题描述 投票:0回答:2
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>
});

我尝试使用refReact.useImperativeHandle()在父组件中使用子方法。

效果很好。

但是由于const cntEl:any,我不满意。

我相信有很多方法可以避免使用我不知道的any类型。

我只需要可以替换的类型any

已编辑

当我将鼠标悬停在(property) React.MutableRefObject<null>.current: null时可以看到cntEl.current

reactjs typescript
2个回答
1
投票

无需将cntEl键入为any。另外,您可以将Countdown用作useRef

的类型通用参数
const cntEl = React.useRef<Countdown>(null);

0
投票

尝试:

const ref1 = useRef<HTMLElement>(null!);
const ref2 = useRef<HTMLElement | null>(null);

[使用useRef时,创建没有初始值的引用容器时,有两个选择:

第一个选项将使ref1.current 只读,并打算传递到React将管理的内置ref属性中(因为React会为您设置当前值)。

第二个选项将使ref2.current mutable,并用于您自己管理的“实例变量”。

我建议检查React Typescript Cheatsheet

© www.soinside.com 2019 - 2024. All rights reserved.