我想在html文件中使用react组件。它用于微前端。所以我按照这个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);
});
上面的代码工作得很好,但我想转换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