为什么尝试在 React 中使用 ref 时 TypeScript 会抱怨?

may*_*513 6 javascript node.js typescript reactjs use-ref

我正在使用 ref 来为滚动上的元素设置动画。

  const foo = () => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    setAnimClass(
      rect.top >= 0 && rect.bottom <= window.innerHeight ? styles.animClass : ""
    );
  };
Run Code Online (Sandbox Code Playgroud)

这段代码在 next.js 应用程序中运行良好,但是当我在类型脚本模板中使用它时create-react-app,它抱怨Object is possibly 'null'.

if (!ref.current) return;明显,如果 ref.current 不存在,则程序将被返回。但是,TypeScript 在下一行仍然给出错误ref.current.getBoundingClientRect(),指向ref.

如何在不删除打字稿配置中的空检查的情况下解决此问题?

完整文件 - https://github.com/mayank1513/react-contact-app/blob/master/src/components/ContactListItem.tsx

这是完整的项目存储库 - https://github.com/mayank1513/react-contact-app

到目前为止,我已经"strict": false在 tsconfig 中使用绕过了这个问题。但我需要以严格模式进行。

该文件中也存在类似问题。即使在 tsconfig 中设置也无法解决这个问题"strict": false。现在,我只是依赖document.getElementById()-- 大约第 65 行

Sak*_*shi 6

尝试这个:

const ref = useRef() as RefObject<HTMLDivElement>;

const foo = () => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    setAnimClass(
      rect.top >= 0 && rect.bottom <= window.innerHeight ? styles.animClass : ""
    );
  };
Run Code Online (Sandbox Code Playgroud)


dem*_*tis 5

你可以将 ref 转换为任何从 React 中获得的值。
const ref = useRef(null) as any;

编辑:我想回来提供一个更强类型的解决方案,但 Sakshi 的答案就是这样做的。这是懒惰的修复,因此请遵循他们的解决方案。