分享react demo片段的时候,如果是整个工程项目就有点太麻烦了,打开速度慢,文件多且没必要,这个时候用html就很方便。
在html中能正常使用useState
和useEffect
等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">