首先按照官方文档一分钟用上React
以及快速尝试JSX
,如果你不需要JSX
,可以按照这个Demo
去实现
我们在页面上放入这三个cdn
:
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
然后新建一个script
标签并指定type="text/babel"
,例如:
<script src="ruben.js" type="text/babel"></script>
然后我们编写代码
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<div id="filterable_product_table"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<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="https://unpkg.com/babel-standalone@6/babel.min.js" crossorigin></script>
<!-- Load our React component. -->
<script src="ruben.js" type="text/babel"></script>
</body>
</html>
ruben.js
:
'use strict';
function LikeButton() {
const [liked, setLiked] = React.useState(false)
if (liked) {
return 'You liked this.';
}
return (
<button onClick={() => setLiked(true)} >
Like
</button>
);
}
ReactDOM.render(<LikeButton />, document.querySelector('#like_button_container'))
然后就可以预览看看效果啦!
点击按钮后,state
变为了true
,且页面也发生了对应变化