ReactJS - Web 组件
React 和 Web 组件可以在 Web 应用程序中混合使用。React 组件可以有一个或多个 Web 组件,Web 组件可以使用 React 组件来创建其内容。React 支持这两种选项。
在 React 应用程序中使用 Web 组件
让我们创建一个 Web 组件,然后尝试将其应用于 React 应用程序中。首先,创建一个新的 React 应用程序并使用以下命令启动它。
create-react-app myapp cd myapp npm start
接下来,打开 App.css (src/App.css) 并删除所有 CSS 类。
// 删除所有 css 类
接下来,创建一个简单的 Web 组件 HelloMessage (public/WebComponents/HelloMessage.js) 并添加以下代码。Web 组件 () 的目的是欢迎用户(通过在 Web 组件的 name 属性中指定用户名)。
// Web 组件 class HelloMessage extends HTMLElement { constructor() { super(); this.name = 'Folks'; } static get observedAttributes() { return ['name']; } attributeChangedCallback(property, oldValue, newValue) { if (oldValue === newValue) return; this[property] = newValue; } connectedCallback() { this.textContent = `Hello ${this.name}!`; } } customElements.define('hello-message', HelloMessage);
此处,
connectedCallback() 用于创建 Web 组件的内容。
observedAttributes 函数访问名称属性。
attributeChangedCallback 函数更新名称属性的值(如果在应用程序中发生更改)。
customElements.define 用于将创建的带有标签名称的 Web 组件附加到 Web 文档中。
接下来,打开 index.html (public/index.html) 文件并添加 Web 组件,如下所示 −
<!DOCTYPE html> <html lang="en"> <head> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <script src="%PUBLIC_URL%/WebComponents/HelloMessage.js"></script> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div style="padding: 10px;"> <div id="root"></div> <div style="padding: 10px;"> <hello-message name="John"></hello-message> </div> </div> </body> </html>
这里我们有,
在 head 部分包含 Web 组件
在页面中使用 hello-message Web 组件来展示它的用法
接下来,创建一个简单的组件 SimpleWebComponent (src/Components/SimpleWebComponent.js) 并呈现新创建的 Web 组件,如下所示 −
import React from "react"; class SimpleWebComponent extends React.Component { constructor(props) { super(props) } render() { return ( <hello-message name="Peter"></hello-message> ); } } export default SimpleWebComponent;
这里,组件的 render 方法中使用了 Web 组件 hello。
接下来,打开 App 组件 (src/App.js),并使用 SimpleWebComponent 组件,如下所示 −
import './App.css' import React from 'react'; import SimpleWebComponent from './Components/SimpleWebComponent' function App() { return ( <div className="container"> <div style={{ padding: "10px" }}> <div> <SimpleWebComponent /> </div> </div> </div> ); } export default App;
这里我们有,
从 react 包中导入 SimpleWebComponent 组件
使用 SimpleWebComponent 组件并渲染 hello web 组件
最后,在浏览器中打开应用程序并检查最终结果。

总结
React 和 web 组件以很好的方式相互补充。每个都有自己的优点和缺点,可以通过分析其相对于应用程序的优缺点在单个应用程序中使用。