繁体   English   中英

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

[英]How can I avoid a TypeScript error with React useRef?

使用 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>

@ts-ignore抑制错误Object is possibly 'null'. 是否可以在不出错的情况下编写此代码?

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

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

if (el && el.current){
  const { top, width } = el.current.getBoundingClientRect();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM