如何使用 React useRef 避免 TypeScript 错误?

anb*_*nyc 8 typescript reactjs react-hooks

使用 React Hooks,当我将 ref 初始化为 null 时遇到 TypeScript 错误,然后尝试稍后访问它。这是一个精简的说明性示例:

  const el = useRef(null);

  useEffect(() => {
    if (el.current !== null) {
      //@ts-ignore
      const { top, width } = el.current.getBoundingClientRect();
    }
  }, []);

  return <div ref={el}></div>
Run Code Online (Sandbox Code Playgroud)

@ts-ignore抑制的错误Object is possibly 'null'.是否有可能写这个没有得到这个错误吗?

anb*_*nyc 9

我在这里找到了答案:https : //fettblog.eu/typescript-react/hooks/#useref

关键是给 ref: 分配一个类型: const el = useRef<HTMLDivElement>(null); 然后仔细检查:

if (el && el.current){
  const { top, width } = el.current.getBoundingClientRect();
}
Run Code Online (Sandbox Code Playgroud)

  • 深入解释[此处](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/38228#issuecomment-529749802)。 (2认同)