You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React 19 TypeScript自定义Web Component类型失效问题修复咨询

React 19 中适配 Web Component 的 JSX 类型定义修复方案

问题说明

在 React 18 中,通过全局声明 JSX.IntrinsicElements 可正常适配自定义 Web Component 的类型,但升级到 React 19 后,该类型定义不再生效,尽管相关类型仍能全局访问。

修复方案

React 19 对 Web Component 的类型处理逻辑做了调整,需按以下方式修改类型声明:

  • 修正拼写错误:原代码中 custom-compoenent 存在拼写错误,应为 custom-component,这是导致类型不生效的基础问题之一。
  • 调整 JSX 类型声明结构:React 19 无需嵌套 DetailedHTMLProps,直接使用 React.HTMLAttributes<CustomComponent> 即可完成类型映射;也可借助 HTMLElementTagNameMap 的关联关系简化定义。

修正后的完整代码

declare global {
  class CustomComponent extends HTMLElement {
    // 可在此添加组件的属性、方法类型定义
  }

  interface HTMLElementTagNameMap {
    "custom-component": CustomComponent;
  }

  namespace JSX {
    interface IntrinsicElements {
      // 方式1:直接使用 HTMLAttributes 完成类型映射
      "custom-component": React.HTMLAttributes<CustomComponent>;
      // 方式2:借助已有元素类型扩展(适合需要复用基础属性的场景)
      // "custom-component": React.JSX.IntrinsicElements["div"] & {
      //   // 自定义属性可在此补充
      //   customProp?: string;
      // };
    }
  }
}

export {}; // 确保文件为模块,避免全局声明冲突

关键注意点

  • React 19 优化了 Web Component 的类型推断逻辑,直接使用 React.HTMLAttributes<T> 即可正确映射组件的原生属性与事件类型。
  • 全局声明必须放在模块文件中(即包含 export {} 或其他导出语句),否则 TypeScript 无法正确识别这些声明。
  • 若自定义组件有额外的自定义属性/事件,可在 IntrinsicElements 的对应接口中补充,示例:
    "custom-component": React.HTMLAttributes<CustomComponent> & {
      customProp: string;
      onCustomEvent: (event: CustomEvent) => void;
    };
    

内容的提问来源于stack exchange,提问作者Dust shooter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:29:56