【发布时间】: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