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

首頁 > 編程 > JavaScript > 正文

React中如何引入Angular組件詳解

2019-11-19 13:18:29
字體:
來源:轉載
供稿:網友

前言

為了在我的編輯器中使用 Angular,我用 Angular 編寫了一個重命名功能。而為了使用它,我得再次使用一次 customEvent ,而在這個微前端架構的系統中,其事件通訊機制已經相當的復雜。在這部分的代碼進一步惡化之前,我得嘗試有沒有別的方式。于是,我想到了之前在其它組件中使用的 Web Components 技術,而 Angular 6 正好可以支持。

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

HTML 中引入 Web Components

我所需要做的事情也相當的簡單,只需要將我的組件注冊為一個 customElements,稍微改一下 app.module.ts 文件。在這種情況之下,我們就可以構建出獨立于框架的組件。

如下是原始的 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 中傳遞參數: <interact-bar filename="phodal.md"></interact-bar> ,或者監聽對應的 @Output 事件:

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

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

React 中引入 Angular 組件

于是,便使用 create-react-app 創建了一個 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 參數可以成功地傳遞到 Angular 代碼中,而 action 在當前似乎還不行。但是毫無疑問,它在未來是可用的。

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

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

這個時候,我遇到了一個問題,我使用 Angular 構建的這個組件,大概是有 257kb。這個大小的組件,但是有點恐怖。

Web Components 框架構建組件

在那些微前端相關的文章中,我們指出類似于 Stencil 的形式,將組件直接構建成 Web Components 形式的組件,隨后在對應的諸如,如 React 或者 Angular 中直接引用。

如下是一個使用 Stencil 寫的 Web Components 的例子:

@Component({ tag: 'phodit-header', styleUrl: 'phodit-header.css'})export class PhoditHeader { @State() showCloseHeader = false; componentDidLoad() {...} handleClick() {...} render() { if (this.showCloseHeader) {...} return (<div></div>); }}

使用它構建出來的組件,大概可以在 30kb 左右的大小。

不論是不是一個經量級的方案,但是它至少證明了組件復用的可行性。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 泰来县| 古蔺县| 潮州市| 门头沟区| 布尔津县| 泾源县| 德令哈市| 醴陵市| 嘉黎县| 辽源市| 怀宁县| 贵德县| 巍山| 城步| 富裕县| 华蓥市| 马尔康县| 长沙县| 奉化市| 股票| 青河县| 泸溪县| 怀远县| 渭源县| 平潭县| 东平县| 渭源县| 富锦市| 禹城市| 洛浦县| 东乡县| 美姑县| 五大连池市| 宜良县| 巴楚县| 忻城县| 辽阳市| 德兴市| 库尔勒市| 黄石市| 台北市|