【问题标题】:Can't get value of HTMLElement无法获取 HTMLElement 的值
【发布时间】:2021-08-03 04:42:24
【问题描述】:

我目前正在使用带有 .tsx 文件的 Ionic React。当我做一个简单的document.getElementById("input-id").value 时,得到了错误Property 'value' does not exist on type 'HTMLElement'。寻找解决这个问题的方法,找到打字稿解析器<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>
  );
}

【问题讨论】:

    标签: reactjs typescript ionic5 tsx


    【解决方案1】:

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

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

    【讨论】:

    • 我在 TypeScript 操场上尝试了这段代码,没有出现类型错误。 typescriptlang.org/play?#code/…
    • 它工作了~啊啊啊我现在太高兴了~谢谢,先生
    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2012-05-02
    • 2011-02-25
    • 2019-03-27
    相关资源
    最近更新 更多