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

React与Angular中自定义元素的正确使用方法咨询

React项目中直接使用<custom-tag>的解决方法

遇到Property 'custom-tag' does not exist on type 'JSX.IntrinsicElements'错误,是因为TypeScript默认不识别自定义HTML元素,只需扩展JSX类型声明即可:

  • 在项目根目录或src文件夹下创建一个类型声明文件,比如custom-elements.d.ts
  • 在文件中添加以下代码,声明你的自定义元素类型:
declare namespace JSX {
  interface IntrinsicElements {
    'custom-tag': React.HTMLAttributes<HTMLElement> & {
      // 这里可以添加自定义元素的专属属性,比如:
      // title?: string;
      // onCustomEvent?: () => void;
    };
  }
}
  • 检查项目的tsconfig.json,确保include数组包含这个.d.ts文件(通常默认会包含src/**/*.d.ts)

完成后就能直接在JSX中使用<custom-tag>标签,无需再用React.createElement。

Angular项目中使用<custom-tag>的正确方式

遇到'custom-tag' is not a known element错误,按以下步骤解决:

步骤1:注册自定义元素

首先确保自定义元素已在Angular项目中注册。如果是通过reactToWebComponent打包的组件,在项目的入口文件(比如main.ts)中导入并执行注册逻辑:

// 替换成你的自定义元素注册方法
import { defineCustomElements } from 'your-custom-element-lib';

defineCustomElements(window);

步骤2:允许未知元素

在使用<custom-tag>的组件所在模块中,导入并添加CUSTOM_ELEMENTS_SCHEMA,告诉Angular允许使用自定义元素:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }

额外提示

  • 绑定自定义元素的属性时,若属性是自定义DOM属性,使用[attr.custom-attr]="value";若元素定义了对应的JS属性,可直接用[customProp]="value"
  • 监听自定义元素的事件,使用Angular的事件绑定语法,比如(customEvent)="handleEvent($event)"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 20:40:27