解决React报错Property 'X' does not exist on type 'HTMLElement'

 更新时间:2022年12月05日 10:27:47   作者:Borislav Hadzhiev  
这篇文章主要为大家介绍了解决React报错Property 'X' does not exist on type 'HTMLElement',有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

总览

在React中,当我们试图访问类型为HTMLElement 的元素上不存在的属性时,就会发生Property 'X' does not exist on type 'HTMLElement'错误。为了解决该错误,在访问属性之前,使用类型断言来正确地类型声明元素。

这里有三个例子来展示错误是如何发生的。

// App.tsx
import {useEffect} from 'react';
export default function App() {
  useEffect(() => {
    const input = document.getElementById('first_name');
    // ⛔️ Property 'value' does not exist on type 'HTMLElement'.ts(2339)
    console.log(input?.value);
    // -----------------------------------------------------------------
    const link = document.getElementById('link');
    // ⛔️ Property 'href' does not exist on type 'HTMLElement'.ts(2339)
    console.log(link?.href);
    // -----------------------------------------------------------------
    const button = document.getElementById('btn');
    if (button != null) {
      // ⛔️ Property 'disabled' does not exist on type 'HTMLElement'.ts(2339)
      button.disabled = true;
    }
  }, []);
  return (
    <div>
      <input
        id="first_name"
        type="text"
        name="first_name"
        defaultValue="Initial Value"
      />
      <a id="link" href="<https://google.com>" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  target="_blank" rel="noreferrer">
        Open Google
      </a>
      <button id="btn">Submit</button>
    </div>
  );
}

产生错误的原因是,document.getElementById方法的返回类型是HTMLElement | null,但是我们试图访问的属性不存在于HTMLElement 类型。

类型断言

为了解决这个错误,使用类型断言来为元素正确地进行类型声明。比如说,类型断言为HTMLInputElementHTMLButtonElementHTMLAnchorElementHTMLImageElementHTMLDivElementHTMLTextAreaElement等等。这取决于你所处理的元素。

这些类型始终命名为HTML***Element 。一旦你开始输入HTML…,你的IDE将会帮你自动补全。

import {useEffect} from 'react';
export default function App() {
  useEffect(() => {
    // ✅ type elements correctly via type assertions
    const input = document.getElementById('first_name') as HTMLInputElement;
    console.log(input?.value);
    const link = document.getElementById('link') as HTMLAnchorElement;
    console.log(link?.href);
    const button = document.getElementById('btn') as HTMLButtonElement;
    if (button != null) {
      button.disabled = true;
    }
  }, []);
  return (
    <div>
      <input
        id="first_name"
        type="text"
        name="first_name"
        defaultValue="Initial Value"
      />
      <a id="link" href="<https://google.com>" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  target="_blank" rel="noreferrer">
        Open Google
      </a>
      <button id="btn">Submit</button>
    </div>
  );
}

类型断言被用于我们知道值的类型信息,但是TypeScript却不知道的时候。

我们明确的告诉TypeScript,input变量上存储了HTMLInputElement ,并让TS不要担心。

同样的,我们将link变量类型声明为HTMLAnchorElement,将btn变量类型声明为HTMLButtonElement

你可以在访问一个属性之前,内联使用类型断言。

import {useEffect} from 'react';
export default function App() {
  useEffect(() => {
    const value = (document.getElementById('first_name') as HTMLInputElement).value;
    console.log(value);
  }, []);
  return (
    <div>
      <input
        id="first_name"
        type="text"
        name="first_name"
        defaultValue="Initial Value"
      />
      <a id="link" href="<https://google.com>" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  target="_blank" rel="noreferrer">
        Open Google
      </a>
      <button id="btn">Submit</button>
    </div>
  );
}

如果你只需要访问属性一次,并且不希望将元素分配给变量,那么内联类型声明可以完成这项工作。

如果你想更精确地处理元素的类型,可以使用联合类型将类型声明为HTML***Element | null

import {useEffect} from 'react';
export default function App() {
  useEffect(() => {
    const input = document.getElementById(
      'first_name',
    ) as HTMLInputElement | null;
    console.log(input?.value);
    const link = document.getElementById('link') as HTMLAnchorElement | null;
    console.log(link?.href);
    const button = document.getElementById('btn') as HTMLButtonElement | null;
    if (button != null) {
      button.disabled = true;
    }
  }, []);
  return (
    <div>
      <input
        id="first_name"
        type="text"
        name="first_name"
        defaultValue="Initial Value"
      />
      <a id="link" href="<https://google.com>" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  target="_blank" rel="noreferrer">
        Open Google
      </a>
      <button id="btn">Submit</button>
    </div>
  );
}

HTML***Element 或者null 类型是最准确的类型,因为如果DOM元素上不存在id属性,那么document.getElementById()将会返回null

你可以使用可选链操作符(?.)在访问属性之前来进行短路运算,如果引用是空值(null或者undefined)的话。

或者,你可以使用简单的if语句作为类型守卫,就像我们对button处理的那样。

总结

最佳实践是在类型断言中包含null 。因为如果元素上面不提供id属性,那么getElementById方法将会返回null

以上就是解决React报错Property 'X' does not exist on type 'HTMLElement'的详细内容,更多关于React报错解决Property X的资料请关注脚本之家其它相关文章!

相关文章

  • useReducer createContext代替Redux原理示例解析

    useReducer createContext代替Redux原理示例解析

    这篇文章主要为大家介绍了useReducer createContext代替Redux原理示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • React生命周期原理与用法踩坑笔记

    React生命周期原理与用法踩坑笔记

    这篇文章主要介绍了React生命周期原理与用法,结合实例形式总结分析了react生命周期原理、用法及相关注意事项,需要的朋友可以参考下
    2020-04-04
  • React组件refs的使用详解

    React组件refs的使用详解

    这篇文章主要介绍了React组件refs的使用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • React Hooks使用常见的坑

    React Hooks使用常见的坑

    React Hooks 是 React 16.8 引入的新特性,允许我们在不使用 Class 的前提下使用 state 和其他特性。接下来通过本文给大家分享React Hooks使用避坑指南,一起学习下吧
    2021-06-06
  • React 实现拖拽功能的示例代码

    React 实现拖拽功能的示例代码

    这篇文章主要介绍了React 实现拖拽功能的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • antd upload上传如何获取文件宽高

    antd upload上传如何获取文件宽高

    这篇文章主要介绍了antd upload上传如何获取文件宽高问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • redux功能强大的Middleware中间件使用学习

    redux功能强大的Middleware中间件使用学习

    这篇文章主要为大家介绍了redux功能强大的Middleware中间件使用学习,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • React 进入页面后自动 focus 到某个输入框的解决方案

    React 进入页面后自动 focus 到某个输入框的解决方案

    React.js 当中提供了 ref 属性来帮助我们获取已经挂载的元素的 DOM 节点,你可以给某个 JSX 元素加上 ref属性,这篇文章主要介绍了React 进入页面以后自动 focus 到某个输入框,需要的朋友可以参考下
    2024-02-02
  • 详解如何在React中有效地监听键盘事件

    详解如何在React中有效地监听键盘事件

    React是一种流行的JavaScript库,用于构建用户界面,它提供了一种简单而灵活的方式来创建交互式的Web应用程序,在React中,我们经常需要监听用户的键盘事件,以便根据用户的输入做出相应的反应,本文将向您介绍如何在React中有效地监听键盘事件,并展示一些常见的应用场景
    2023-11-11
  • 浅谈箭头函数写法在ReactJs中的使用

    浅谈箭头函数写法在ReactJs中的使用

    这篇文章主要介绍了浅谈箭头函数写法在ReactJs中的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08

最新评论