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
相关产品推荐
相关产品推荐

