阿超
>
在单html页面中使用react并配置jsx
天空更适合仰望,而不是居住。——杜鲁门·卡波特 《蒂凡尼的早餐》
首先按照官方文档一分钟用上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>
<div id="like_button_container"></div>
<div id="filterable_product_table"></div>
<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>
<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'))
|
然后就可以预览看看效果啦!
点击按钮后,state
变为了true
,且页面也发生了对应变化