国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

React中如何引入Angular組件詳解

2024-05-06 15:32:00
字體:
供稿:網(wǎng)友

前言

為了在我的編輯器中使用 Angular,我用 Angular 編寫了一個(gè)重命名功能。而為了使用它,我得再次使用一次 customEvent ,而在這個(gè)微前端架構(gòu)的系統(tǒng)中,其事件通訊機(jī)制已經(jīng)相當(dāng)?shù)膹?fù)雜。在這部分的代碼進(jìn)一步惡化之前,我得嘗試有沒有別的方式。于是,我想到了之前在其它組件中使用的 Web Components 技術(shù),而 Angular 6 正好可以支持。

下面話不多說了,來一起看看詳細(xì)的介紹吧

HTML 中引入 Web Components

我所需要做的事情也相當(dāng)?shù)暮?jiǎn)單,只需要將我的組件注冊(cè)為一個(gè) customElements,稍微改一下 app.module.ts 文件。在這種情況之下,我們就可以構(gòu)建出獨(dú)立于框架的組件。

如下是原始的 module 文件:

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

如下則是新的 module 文件:

@NgModule({ declarations: [InteractBar], imports: [BrowserModule], entryComponents: [InteractBar]})export class AppModule { constructor(private injector: Injector) { const interactBar = createCustomElement(InteractBar, {injector}); customElements.define('interact-bar', interactBar); }}

然后,只需要就可以在 HTML 中傳遞參數(shù): <interact-bar filename="phodal.md"></interact-bar> ,或者監(jiān)聽對(duì)應(yīng)的 @Output 事件:

const bar = document.querySelector('interact-bar');bar.addEventListener('action', (event: any) => { ...})

事實(shí)證明,使用 Angular 構(gòu)建的 Web Components 組件是可以用的。于是,我便想,不如在 React 中引入 Angular 組件吧。

React 中引入 Angular 組件

于是,便使用 create-react-app 創(chuàng)建了一個(gè) DEMO,然后引入組件:

<div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload.  <interact-bar filename="phodal.com" onAction={this.action}></interact-bar> </p></div>

嗯,it works。至少 filename 參數(shù)可以成功地傳遞到 Angular 代碼中,而 action 在當(dāng)前似乎還不行。但是毫無疑問,它在未來是可用的。

Demo 見: https://phodal.github.io/wc-angular-demo/

Repo 見: https://github.com/phodal/wc-angular-demo

這個(gè)時(shí)候,我遇到了一個(gè)問題,我使用 Angular 構(gòu)建的這個(gè)組件,大概是有 257kb。這個(gè)大小的組件,但是有點(diǎn)恐怖。

Web Components 框架構(gòu)建組件

在那些微前端相關(guān)的文章中,我們指出類似于 Stencil 的形式,將組件直接構(gòu)建成 Web Components 形式的組件,隨后在對(duì)應(yīng)的諸如,如 React 或者 Angular 中直接引用。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 莲花县| 平泉县| 周至县| 故城县| 涟水县| 仁寿县| 新乡县| 太仆寺旗| 湟源县| 高淳县| 威宁| 玛多县| 海丰县| 专栏| 汝州市| 加查县| 卢龙县| 宿迁市| 色达县| 无棣县| 娄烦县| 库伦旗| 朔州市| 日土县| 旌德县| 四川省| 双牌县| 波密县| 伊通| 临泽县| 无锡市| 凉山| 大田县| 定兴县| 礼泉县| 临沭县| 都匀市| 呼和浩特市| 永和县| 东山县| 沽源县|