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

如何在Angular项目中使用已发布到NPM的React组件?

在Angular项目中使用React组件的实现方案

1. 安装必要依赖

在Angular项目根目录执行以下命令,安装React核心依赖、你的NPM组件包及TypeScript类型定义:

npm install react react-dom your-react-component-package
npm install --save-dev @types/react @types/react-dom

2. 调整TypeScript配置

修改项目根目录的tsconfig.json,添加React语法支持相关配置:

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}

3. 创建Angular封装组件

新建一个Angular组件作为React组件的容器,处理渲染、生命周期和数据传递逻辑:

import { Component, Input, Output, EventEmitter, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { render, unmountComponentAtNode } from 'react-dom';
import YourReactComponent from 'your-react-component-package';

@Component({
  selector: 'app-react-wrapper',
  template: `<div #reactContainer></div>`
})
export class ReactWrapperComponent implements OnInit, OnDestroy {
  @Input() componentProps: Record<string, any> = {};
  @Output() componentEvent = new EventEmitter<any>();

  private container: HTMLElement;

  constructor(private elRef: ElementRef) {
    this.container = this.elRef.nativeElement.querySelector('#reactContainer');
  }

  ngOnInit(): void {
    // 渲染React组件,传入props和事件回调
    render(
      <YourReactComponent 
        {...this.componentProps}
        onTriggerEvent={(data) => this.componentEvent.emit(data)}
      />,
      this.container
    );
  }

  ngOnDestroy(): void {
    // 卸载React组件,避免内存泄漏
    unmountComponentAtNode(this.container);
  }
}

4. 在Angular项目中使用封装组件

在目标Angular组件的模板中直接调用封装后的组件,传递参数并监听事件:

<app-react-wrapper 
  [componentProps]="{ label: '测试React组件', defaultValue: 'demo' }"
  (componentEvent)="handleReactEvent($event)"
></app-react-wrapper>

在组件类中添加事件处理方法:

handleReactEvent(data: any): void {
  console.log('React组件触发事件:', data);
}

5. 解决编译兼容性问题(若遇到报错)

如果Angular CLI编译时出现React语法解析错误,需配置自定义Webpack规则:

  1. 安装相关依赖:
npm install --save-dev @angular-builders/custom-webpack babel-loader @babel/preset-react
  1. 新建项目根目录的webpack.config.js:
module.exports = {
  module: {
    rules: [
      {
        test: /\.(jsx|js)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react']
          }
        }
      }
    ]
  }
};
  1. 修改angular.json中的构建配置,替换为自定义Webpack构建器:
"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
      // 保留原有其他配置
    }
  },
  "serve": {
    "builder": "@angular-builders/custom-webpack:dev-server"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:05:44