![](/img/trans.png)
[英]How can I convert this Class component function into functional component in React Native
[英]How can I convert class component into functional component when adding React library to a Website?
我想在 html 文件中使用反應組件。 它適用於微前端。 所以我按照這個 React 官方文檔將 React 添加到網站。
示例代碼如下:
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);
});
上面的代碼工作正常,但我想將class組件 like_button.js 轉換為功能組件。
提前致謝。
您需要使用babel standalone script
來轉換代碼,並且需要包含react
和react-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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.