使用 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'.是否有可能写这个没有得到这个错误吗?