/
stateDemo.html
57 lines (50 loc) · 1.39 KB
/
stateDemo.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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/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 Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date()
};
}
// React 组件生命周期函数,在render()之后
componentDidMount() {
this.timerId = setInterval(
() => this.tick(),
1000
)
}
// React 组件生命周期函数,在组件卸载(unmounted)或销毁(destroyed)之前
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1> Hello World! </h1>
<h2> It is {this.state.date.toLocaleTimeString()} </h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
</script>
</body>
</html>