[Day16] - 利用 direflow.io 将 React Component 转换成 Web Component

昨天解说 Vue 如何制作 Web-Component 今天来说明一下 ,

那 React 如何制作 Web-Component 呢 ? 可以利用 direflow.io


one 利用 direflow.iodireflow create 建立专案

参考 direflow.io - 官方网站

$ npm i -g direflow-cli
$ direflow create my-app
$ cd my-app
$ npm start

create react app

two 建立一个 React Component

import React from 'react';
import PropTypes from 'prop-types';
import {Styled} from 'direflow-component';
import styles from './App.css';

class App extends React.Component {

  state = {timer: 10}

  constructor() {
    super();

    console.log(this.props)
    this.state.timer = this.props?.timer || 10
  }

  componentDidMount() {

    setInterval(() => this.setState({timer: this.state.timer - 1}), 1000)
  }

  render() {

    return (
      <Styled styles={styles}>
        <div className="box">
          <div className="circle circle1"></div>
          <div className="circle circle2"></div>
          <div className="number">{this.state?.timer}</div>
          <div className="niddle"></div>
        </div>
      </Styled>
    );
  }
}

App.defaultProps = {timer: 10,}

App.propTypes = {
  timer: PropTypes.number,
};

export default App;

three 利用 DireflowComponent.create 来设定要建立的 Web Component

import { DireflowComponent } from 'direflow-component';
import App from './App.jsx';

export default DireflowComponent.create({
  component: App,
  configuration: {
    tagname: 'film-countdown',
  },
});

four 利用 npm run build 建立 Web Component

$ npm run build

我们看到 build 资料夹中多了一个 direflowBundle.js 的档案

build-folder

将建立出来的 direflowBundle.js 引入到 html 中 , 即可使用 <film-countdown> 这个 custom-tag

<body style="margin: 0">

<film-countdown timer="40"></film-countdown>

<script src="./direflowBundle.js"></script>
</body>

成果

count-down

如果想直接体验成果 , 请到 react-web-component.html 查看

参考资料


<<:  [拯救上班族的 Chrome 扩充套件] 你渴望猫咪吗?那就把猫咪插入到每个页面吧!

>>:  Day 5 他国气象局网站分析(加、日、台)

[Day 21] - 『转职工作的Lessons learned』 - GraphQL (Hasura) - Event Trigger

今天要继续讲一下GraphQL(Hasura)里面的一个小功能 - Event Trigger。 会...

成为工具人应有的工具包-09 IECookiesView 01

IECookiesView 01 ok 今天又要来认识什麽工具呢? 下一个顺位是这个 乳题 IECo...

.NET Core第17天_LabelTagHelper的使用

LabelTagHelper的使用 对应於HTML tag的封装,用於给予对应的显示名称。 当中的f...

Day 27 |> Elixir 并行性 (一)

这篇不承接上一篇,因为时间太赶了,所以来看 Elixir 并行程序的部分。 Elixir 的 Pro...

Day22 ( 高级 ) 猫咪万花筒

猫咪万花筒 教学原文参考:猫咪万花筒 这篇文章会介绍,在 Scratch 3 里使用扩充功能的画笔,...