html引入react以及hook的使用

html引入react

效果

分享react demo片段的时候,如果是整个工程项目就有点太麻烦了,打开速度慢,文件多且没必要,这个时候用html就很方便。

在html中能正常使用useStateuseEffect 等hook。

代码

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React App</title>
</head>
<body>
  <div id="root"></div>
  <script crossorigin src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

  <script type="text/babel">

    function App() {
        const [count, setCount] = React.useState(0);

        React.useEffect(() => {
        console.log('Component is mounted');
        return () => {
          console.log('Component will unmount');
        };
      }, []); 

      return (
        <div>
          <h1>Hello, React!</h1>
          <p>This is a simple React component.</p>
          <p>开始数字{count} </p>
                <button onClick={() => setCount(count + 1)}>
                    点击
          </button>
        </div>
      );
    };

    ReactDOM.render(<App />, document.getElementById('root'));
  </script>
</body>
</html>

注意

这一段很重要,type="text/babel" 和 cdn 引用错误会导致失效。

复制代码
  <script crossorigin src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
	<script type="text/babel">
相关推荐
周航宇JoeZhou1 天前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
代码小库1 天前
【课程作业必备】Web开发技术HTML静态网站模板 - 校园动漫社团主题完整源码
前端·html
VT.馒头1 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
云计算DevOps-韩老师1 天前
HTML 中的行级元素(inline)、块级元素(block)、行内块元素(inline-block)
html
珹洺1 天前
Bootstrap-HTML(二)深入探索容器,网格系统和排版
前端·css·bootstrap·html·dubbo
BillKu1 天前
VS Code HTML CSS Support 插件详解
前端·css·html
xixixin_1 天前
【React】中 Body 类限定法:优雅覆盖挂载到 body 的组件样式
前端·javascript·react.js
摘星编程1 天前
用React Native开发OpenHarmony应用:Image网络图片加载
javascript·react native·react.js
摘星编程1 天前
OpenHarmony环境下React Native:ImageBase64图片显示
javascript·react native·react.js
阿蒙Amon1 天前
TypeScript学习-第13章:实战与最佳实践
javascript·学习·typescript