小编anb*_*nyc的帖子

如何使用 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>
Run Code Online (Sandbox Code Playgroud)

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

typescript reactjs react-hooks

8
推荐指数
1
解决办法
5324
查看次数

标签 统计

react-hooks ×1

reactjs ×1

typescript ×1