react class组件简单使用实例
- react dom 渲染
- this.setState的使用(包含简单数据dom更新)
- dom简单事件挂载
<!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">
// 类组件,也称之为有状态组件
class ClassCom extends React.Component {
constructor(){
// 使用this前必须调用super()
super()
// 定义当前组件的局部状态==> 相当于vue组件中的data
this.state={
timer:new Date().toLocaleString(),
name:'张三'
}
}
updateTime(){
this.interval = setInterval(()=>{
// 使用setState方法来更新局部数据
// setState() 传递一个对象 这个对象会和this.state这个对象进行浅合并
this.setState({
timer:new Date().toLocaleString()
})
},100)
setTimeout(()=>{this.setState({
name:'李四'
})},1000)
}
// 组件挂载之后==>相当于vue中的 mounted
componentDidMount(){
this.updateTime()
}
// 组件即将卸载==>相当于vue中的beforeDestroy
componentWillUnmount(){
//卸载定时器
clearInterval(this.interval)
}
//这是react生命周期中的一个钩子函数,这里会进行diff算法和更新虚拟dom
render() {
return(
<div>
<h3>{this.state.name}</h3>
<h5>类组件渲染时间: {this.state.timer}</h5>
</div>
);
}
}
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<ClassCom />);
</script>
</body>
</html>