【发布时间】:2021-04-26 14:46:27
【问题描述】:
我正在使用 ref 为滚动上的元素设置动画。
const foo = () => {
if (!ref.current) return;
const rect = ref.current.getBoundingClientRect();
setAnimClass(
rect.top >= 0 && rect.bottom <= window.innerHeight ? styles.animClass : ""
);
};
此代码在 next.js 应用程序中运行良好。但是当我在create-react-app type-script 模板中使用它时,它抱怨Object is possibly 'null'.
从if (!ref.current) return; 可以清楚地看出,如果 ref.current 不存在,程序将被返回。但是 TypeScript 在下一行 ref.current.getBoundingClientRect() 上仍然给出错误,指向 ref。
如何在不从 typescript 配置中删除 null 检查的情况下解决此问题?
完整文件 - https://github.com/mayank1513/react-contact-app/blob/master/src/components/ContactListItem.tsx
这是完整的项目回购 - https://github.com/mayank1513/react-contact-app
到目前为止,我已经在 tsconfig 中使用 "strict": false 绕过了这个问题。但需要在严格模式下进行。
this 文件中也存在类似问题。即使通过在 tsconfig 中设置 "strict": false 也无法解决此问题。现在我只依赖document.getElementById()——在第 65 行左右
【问题讨论】:
-
可选链接可能会抑制错误
ref?.current?.getBoundingClientRect() -
试试这个。
ref?.current!.getBoundingClientRect()
标签: javascript reactjs typescript use-ref