react函数式组件简单使用实例
- react dom 渲染
- useState的使用(包含简单数据和对象的dom更新)
- dom简单事件挂载
放代码方便大家学习,使用的html,cdn引入
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React Hello World</title>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState } = React;
// 函数组件,无状态组件
function MyApp() {
const [count, setCount] = useState(1);
const [time, setTime] = useState(new Date().toLocaleString());
const [obj,setObj]= useState({name:'张三', age:'21'})
let plus=()=>{
setInterval(()=>{
setCount(prevCount => prevCount + 1)
setTime(new Date().toLocaleString())
},1000)
//class 组件的 this.setState会自动合并更新对象
//useState 不会自动合并更新对象,不会把新的 state 和旧的 state 进行合并,更新 state 变量是完全替换。
//所以要object.assign合并对象或者 {...preVal,{name:'李四'}} 手动合并
setObj((preVal)=>Object.assign(obj,{name:'李四'}))
}
return (
<div>
<h1> {count} </h1>
<h2>时间:{time}</h2>
<h3>姓名:{obj.name} ; 年龄:{obj.age}</h3>
<button onClick={plus}>start plus & start time</button>
</div>
);
}
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<MyApp />);
</script>
</body>
</html>