将 React 库添加到网站时,如何将 class 组件转换为功能组件?

How can I convert class component into functional component when adding React library to a Website?

我想在 html 文件中使用 React 组件。它适用于微前端。所以我按照 Add React to a Website.

的这个反应官方文档

示例代码如下:

index.html

<html>
  <body>
    
    <p>
      This is the first like.
      <div class="like_button_container" data-commentid="1"></div>
    </p>

    <p>
      This is the second like.
      <div class="like_button_container" data-commentid="2"></div>
    </p>

    <p>
      This is the third like.
      <div class="like_button_container" data-commentid="text"></div>
    </p>

    <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>

    <script src="like_button.js"></script>

  </body>
</html>

like_button.js

"use strict";

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {

    return e(
      "button",
      {
        onClick: () =>
          this.setState((prevState) => ({
            liked: !prevState.liked,
          })),
      },
      this.state.liked ? "Liked " + this.props.commentID : "Unliked"
    );
  }
}

document.querySelectorAll(".like_button_container").forEach((domContainer) => {
  const commentID = domContainer.dataset.commentid;
  ReactDOM.render(e(LikeButton, { commentID: commentID }), domContainer);
});

以上代码工作正常,但我想将 like_button.js,即 class 组件转换为功能组件。

提前致谢。

您需要使用 babel standalone script 来转译代码,并且您需要包含 reactreact-dom 的脚本,使用这些就可以了。

<html>
<head>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script crossorigin src="https://unpkg.com/@babel/standalone@7.15.7/babel.min.js"></script>
</head>
<body>
    <div id="react-container"></div>
    <script type="text/babel">
        const App = () => <div>Hello!</div>
        ReactDOM.render(
        <App />, document.getElementById('react-container'))
    </script>
</body>
</html>

Babel Standalone 将 ECMAScript 2015+ 转换为适用于您浏览器的 JavaScript 兼容版本,CDN 用法在官方文档中有描述,请查看 babel standalone 部分:Babel Standalone