reactjs - 如何使用 React useRef 避免 TypeScript 错误?
问题描述
使用 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();
}
推荐阅读
- java - android通过改造上传pdf文件给SSL异常
- python - 如何在 Selenium (Python) 中将打开的页面保存为 pdf
- excel - 保存到 Oracle 数据库的连接
- google-chrome-extension - 弹出窗口没有 openerTabId 属性
- amazon-dynamodb - 跨账户 DynamoDB 访问
- python - 不要使用 pandas 处理来自 CSV 文件的空值
- angularjs - 无法从具有不同选项卡和日期的网站上抓取数据
- sql - 使用逗号分隔符拆分列
- javascript - 如何为所有类型的输入纠正可变长度柯里化函数或一般柯里化函数?
- maven - 当使用具有“addClasspath”属性的 Maven-Jar-plugin 时,Maven 如何在类路径上对依赖项 jar 进行排序?