简体   繁体   English

我可以将 React 组件转换为 Web 组件吗?

[英]Can I transpile a react component to a web component?

I am working on a big angular project and want to use some react components, but since react components can't be used in angular in a proper way, I wonder if I can transpile the react component to a web component and then include the web component in my angular project.我正在做一个大的角度项目,想使用一些反应组件,但由于反应组件不能以正确的方式在角度中使用,我想知道我是否可以将反应组件转换为网络组件,然后包括网络我的角度项目中的组件。

Solution (from Rect DOCS )解决方案(来自Rect DOCS

Encapsulate React in aw eb component , then use the web component in your Angular app.React封装在 aw eb component中,然后在Angular应用程序中使用 web component。 This should fullfill both your requirement:这应该满足您的要求:

  • you do not need to rewrite the parent Angular app你不需要重写父 Angular 应用程序
  • you do not need to rewrite the child React components你不需要重写子 React 组件

Example:例子:

    class XSearch extends HTMLElement {
      connectedCallback() {
        const mountPoint = document.createElement('span');
        this.attachShadow({ mode: 'open' }).appendChild(mountPoint);

        const name = this.getAttribute('name');
        const url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
        ReactDOM.render(<a href={url}>{name}</a>, mountPoint);
      }
    }
    customElements.define('x-search', XSearch);

If you rewrite the react component into a Native Web component without using any frameworks then you can use it in React and Angular and Vue and anything else.如果你在不使用任何框架的情况下将 React 组件重写为 Native Web 组件,那么你可以在 React 和 Angular 以及 Vue 和其他任何东西中使用它。

If/When your company wants to move to a different framework then a native component written in raw JavaScript will still function.如果/当您的公司想要迁移到不同的框架时,那么用原始 JavaScript 编写的本机组件仍然可以运行。

We can include the React component using <script> tag.我们可以使用<script>标签包含 React 组件。 Please follow the below guide provided in React JS docs.请遵循 React JS 文档中提供的以下指南。

https://reactjs.org/docs/add-react-to-a-website.html https://reactjs.org/docs/add-react-to-a-website.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM