iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Modern Web

Web Component 網頁元件之路系列 第 17

[Day17] - 在 React 中引入現成的 Web Component

  • 分享至 

  • twitterImage
  •  

當我們拿到一個現有的 Web Component 時 , 如何在 React 專案中引用呢 ?


one 利用 [create]-react-app](https://github.com/facebook/create-react-app) 建立一個新專案

$ npx create-react-app my-app

建立專案中...

twosrc/index.jsx 中引入要使用的 Web Component ( word-count.js )

// src/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

+ // 只需要做全域 import , 之後你就可以使用定義的 custom element  
+ import './word-count.js';

ReactDOM.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>,
  document.getElementById('root')
);

three 在專案中使用 custom element <word-count>

// src/App.jsx
import './App.css';

function App() {
  return (
    <div className="container">
      <word-count limit="100">
        <h3>個人自介</h3>
        <textarea className="needcount" rows="10" placeholder="請輸入您的個人描述...">
    </textarea>
      </word-count>
    </div>
  );
}

export default App;

four 利用 npm run start 查看引入成果

$ npm run build

成果

word-count

參考資料


上一篇
[Day16] - 在 Vue 中引入現成的 Web Component
下一篇
[Day18] - 打包 Element-UI 的 Vue Component to Web Component
系列文
Web Component 網頁元件之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言