reactjs - 无法获取 HTMLElement 的值
问题描述
我目前正在使用带有 .tsx 文件的 Ionic React。当我做一个简单的document.getElementById("input-id").value
,得到了错误Property 'value' does not exist on type 'HTMLElement'
。寻找解决此问题的方法,找到 typescript parser <HTMLInputElement>
,但不起作用,因为 HTMLElement 没有很多 HTMLInputElement 道具。
在这种情况下如何获取输入的值?
我的代码在这里。由于 Typescript 错误,它甚至无法编译:
handleChange() {
const input = document.getElementById("id").value;
}
render() {
return (
<IonPage>
<IonContent fullscreen>
<TextField
id="id"
label="Input"
variant="outlined"
required
/>
</IonContent>
</IonPage>
);
}
解决方案
您可以使用as
关键字强制转换并声明一个您知道是HTMLInputElement
类型的变量。然后访问它的value
属性。
const inputElement: HTMLInputElement = document.getElementById("input-id") as HTMLInputElement;
console.log(inputElement.value)
推荐阅读
- r - 优化函数对 2 个相似的数据集给出了不正确的结果
- nuxt.js - 如何在 nuxt.js 中使用插件
- json - 如何提取 JSON 数据?我有不同的模式
- c# - 使用 C# 在我的代码中始终不存在记录
- python - ValueError:形状(4,4)和(3,)未对齐:4(dim 1)!= 3(dim 0)
- firebase - 在动态 365 中创建 manifest.json 的替代方法
- java - 在java中返回给定值的任意数字
- python - 每当按下一个键时,就会转到另一个刺激
- jmeter - {"Message":"An error has occurred."} 确切的意思是/错误
- c++ - CAN报文传输时序不一致