首页 > 解决方案 > 无法获取 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>
  );
}

标签: reactjstypescriptionic5tsx

解决方案


您可以使用as关键字强制转换并声明一个您知道是HTMLInputElement类型的变量。然后访问它的value属性。

const inputElement: HTMLInputElement = document.getElementById("input-id") as HTMLInputElement;
console.log(inputElement.value)

推荐阅读