天空更适合仰望,而不是居住。——杜鲁门·卡波特 《蒂凡尼的早餐》

首先按照官方文档一分钟用上React以及快速尝试JSX,如果你不需要JSX,可以按照这个Demo去实现

我们在页面上放入这三个cdn

1
2
3
<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",例如:

1
<script src="ruben.js" type="text/babel"></script>

然后我们编写代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
'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'))

然后就可以预览看看效果啦!

image-20220301185556823

点击按钮后,state变为了true,且页面也发生了对应变化

image-20220301185727520