anb*_*nyc 8 typescript reactjs react-hooks
使用 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'.是否有可能写这个没有得到这个错误吗?
我在这里找到了答案:https : //fettblog.eu/typescript-react/hooks/#useref
关键是给 ref: 分配一个类型:
const el = useRef<HTMLDivElement>(null);
然后仔细检查:
if (el && el.current){
const { top, width } = el.current.getBoundingClientRect();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5324 次 |
| 最近记录: |