【问题标题】:How can I avoid a TypeScript error with React useRef?如何使用 React useRef 避免 TypeScript 错误?
【发布时间】:2020-01-01 02:30:41
【问题描述】:

使用 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'. 是否可以写这个而不得到错误?

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

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

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

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

    【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2016-02-14
    • 2021-11-13
    • 2023-01-03
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    相关资源
    最近更新 更多