简体   繁体   中英

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

I want to use react component in html file. It is for micro frontend. So I follow this react official doc for Add React to a Website .

The sample code is as below:

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);
});

Above code is working fine but I want to convert like_button.js , which is class component into functional component.

Thanks in advance.

You need to use babel standalone script to transcompile the code, and you need to include the script for react and react-dom , use these will work.

<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 converts ECMAScript 2015+ into the compatible version of JavaScript for your browser, CDN usage is described in official documentation, check babel standalone section: Babel Standalone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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