温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React中如何引入Angular组件详解

发布时间:2020-10-15 03:35:38 来源:脚本之家 阅读:219 作者:Phodal全栈工程师 栏目:web开发

前言

为了在我的编辑器中使用 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" />
 <h2 className="App-title">Welcome to React</h2>
 </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 左右的大小。

不论是不是一个经量级的方案,但是它至少证明了组件复用的可行性。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI