首页 > 解决方案 > 如何使用 React useRef 避免 TypeScript 错误?

问题描述

使用 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'.情况下编写它?

标签: reactjstypescriptreact-hooks

解决方案


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

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

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

推荐阅读