React报错之Property 'value' does not exist on type 'HTMLElement'
正文从这开始~
总览
当我们试图访问一个类型为HTMLElement的元素上的value属性时,会产生"Property 'value' does not exist on type 'HTMLElement'"错误。为了解决该错误,在访问属性之前,使用类型断言将元素类型断言为HTMLInputElement。
这里有个示例用来展示错误是如何发生的。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
const input = document.getElementById('message');
// ️ Property 'value' does not exist on type 'HTMLElement'.ts(2339)
console.log(input?.value);
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
我们得到错误的原因是因为,document.getElementById方法返回的类型为HTMLElement | null ,并且value属性不存在于HTMLElement类型上。
类型断言
为了解决该错误,使用类型断言将元素类型断言为HTMLInputElement(或者HTMLTextAreaElement,如果你使用textarea元素键入)。
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
// type element as HTMLInputElement
const input = document.getElementById('message') as HTMLInputElement;
console.log(input?.value); // ️ "Initial value"
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
你也可以在内联中使用一个类型断言,就在访问值属性之前。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
// ️ inline type assertion
const value = (document.getElementById('message') as HTMLInputElement).value;
console.log(value);
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
当我们拥有一个值的类型信息,但是TypeScript无从得知时,就会使用类型断言。
我们有效地告诉TypeScript,
input变量存储了一个HTMLInputElement,不用担心它。
如果你正在使用一个textarea元素,你将使用HTMLTextAreaElement类型来代替。
联合类型
如果你想更精确地控制类型,你可以使用一个联合类型来设置类型为HTMLInputElement | null。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
// type element as HTMLInputElement | null
const input = document.getElementById('message') as HTMLInputElement | null;
console.log(input?.value); // ️ "Initial value"
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
HTMLInputElement | null类型是正确的,因为如果提供id的元素不存在于DOM中,document.getElementById()方法就会返回一个null值。
需要注意的是,我们使用了可选链(?.)操作符来短路运算,如果引用是空值的话(null或者undefined)。
换句话说,如果input变量存储了一个null值,我们就不会试图访问null的属性,而得到一个运行时错误。
类型守卫
你也可以使用一个简单的if语句作为类型守卫,以确保input变量不存储一个null值。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
const input = document.getElementById('message') as HTMLInputElement | null;
if (input != null) {
console.log(input.value); // ️ "Initial value"
}
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
TypeScript知道
input变量在if块中的类型是HTMLInputElement,并允许我们直接访问其value属性。
在类型断言中包含null总是一种最佳实践,因为如果没有找到所提供的id的元素,getElementById方法将返回null。
React报错之Property 'value' does not exist on type 'HTMLElement'的更多相关文章
- React报错之Property 'X' does not exist on type 'HTMLElement'
正文从这开始~ 总览 在React中,当我们试图访问类型为HTMLElement 的元素上不存在的属性时,就会发生Property 'X' does not exist on type 'HTMLEl ...
- React报错之Property 'value' does not exist on type EventTarget
正文从这开始~ 总览 当event参数的类型不正确时,会产生"Property 'value' does not exist on type EventTarget"错误.为了解决 ...
- React报错之Parameter 'props' implicitly has an 'any' type
正文从这开始~ 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an ...
- React报错之Parameter 'event' implicitly has an 'any' type
正文从这开始~ 总览 当我们不在事件处理函数中为事件声明类型时,会产生"Parameter 'event' implicitly has an 'any' type"错误.为了解决 ...
- 解决TS报错Property 'style' does not exist on type 'Element'
在使用queryselector获取一个dom元素,编译时却报错说property 'style' does not exist on type 'element'. 原因:这是typescript的 ...
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- elasticsearch查询:启动项目报错No property ... found for...Did you mean '...'?
网上找的案例是: 实体类字段定义:private String sku_no;dao中接口名定义:Goods findBySkuNo(String skuNo);spring-data按照接口方法定义 ...
- react中使用typescript时,error: Property 'setState' does not exist on type 'Home'
问题描述: 我在react中用typescript时,定义一个Home组件,然后在组件里用setState时会有这样一个报错:(如图)Property 'setState' does not exis ...
- notification 报错the method build() is undefined for the type Notificatin.Builder
notification 报错the method build() is undefined for the type Notificatin.Builder 这事api版本号太低导致的 Notifi ...
随机推荐
- sql语句中 int(1)与int(10)有什么区别?资深开发竟然能理解错
过完春节该投入战斗了,上班第一天发现了一个挺有意思的知识点给大家分享一下:一直以来的的误区我们都认为了int后面的跟的数字为最大显示宽度会对后面插入的参数会有限制,其实倒不是这样的 # 困惑 最近遇到 ...
- MathType7安装使用及please restart word to load mathtype addin properly的问题
MathType7安装使用及please restart word to load mathtype addin properly的问题.最近在自己的电脑上安装Mathtype7,把遇到的问题和解决办 ...
- Java上传文件至SFTP服务器
Windows搭建SFTP服务器 https://www.cnblogs.com/wangjunguang/p/9453611.html 注意点: 1.以管理员权限运行FreeSSHd 2.如果无法启 ...
- 这不会又是一个Go的BUG吧?
hello,大家好呀,我是小楼. 最近我又双叒叕写了个BUG,一个线上服务死锁了,不过幸亏是个新服务,没有什么大影响. 出问题的是Go的读写锁,如果你是写Java的,不必划走,更要看看本文,本文的重点 ...
- UiPath循环活动For Each的介绍和使用
一.For Each的介绍 For Each:循环迭代一个列表.数组.或其他类型的集合, 可以遍历并分别处理每条信息 二.For Each在UiPath中的使用 1. 打开设计器,在设计库中新建一个 ...
- 【数据库Mysql 查询当前时间,年月日】
1.本年份 SELECT YEAR(now()) SELECT DATE_FORMAT(NOW(), '%Y') 2.本月份(例如:1.01.January) SELECT MONTH(now()) ...
- NC25043 [USACO 2007 Jan S]Protecting the Flowers
NC25043 [USACO 2007 Jan S]Protecting the Flowers 题目 题目描述 Farmer John went to cut some wood and left ...
- ABAP BAPI 复制标准项目模板实现项目立项
一.复制标准项目模板实现项目立项 因为CJ20N录屏存在困难,所以想通过BDC实现复制项目模板创建项目立项行不通,因此需要通过BAPI解决. 因为项目立项包含:项目定义.WBS.网络.作业,因此需要分 ...
- 2022-7-11 javascript学习 第七组 刘昀航
JavaScript是什么? 编程语言,脚本语言,依赖于某种容器来运行. JS是运行在浏览器上的,可以帮助我们去控制页面. Vue.js react.js jquery.js an ...
- 性能浪费的日志案例和使用Lambda优化日志案例
有些场景的代码执行后,结果不一定会被使用,从而造成性能浪费.而Lambda表达式是延迟执行的,这正好可以作为解决方案,提升性能 性能浪费的日志案例 日志可以帮助我们快速的定位问题,记录程序运行过程中的 ...