[英]How can I avoid a TypeScript error with React useRef?
使用 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'.
是否可以在不出错的情况下编写此代码?
我在这里找到了答案: https : //fettblog.eu/typescript-react/hooks/#useref
关键是给 ref 分配一个类型: const el = useRef<HTMLDivElement>(null);
然后仔细检查:
if (el && el.current){
const { top, width } = el.current.getBoundingClientRect();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.