-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.html
66 lines (50 loc) · 1.48 KB
/
state.html
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>状态改变</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/babel">
class Clock extends React.Component{
constructor(){
super();//调用父类的构造函数
this.state = {
data:new Date()
}
}
//在组件的生命周期中使用定时器
/*var that = this;
setInterval(
function () {
that.setState({
data:new Date()
})
},1000)*/
componentDidMount(){
//使用ES6的箭头函数,可以不用担心this指向发生改变
this.inteval = setInterval(()=>{
this.setState({
data:new Date()
})
},1000)
}
//添加了定时器之后一定要准备去清除定时器
componentWillUnMount(){
clearInterval(this.inteval);
}
render(){
return(
<div>{this.state.data.toLocaleTimeString()}</div>
)
}
}
let test = <Clock/>;
ReactDOM.render(test,document.getElementById("root"));
</script>
</html>