React初学记录-时间

React APP

Posted by 初学JS的MetaNetworks on February 6, 2020
本页面总访问量

时间走秒

  • state状态机
  • setInterval时间间隔
  • componentDidMountcomponentWillMount生命周期钩子

效果

image-20200206210253563

代码
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
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import {Button} from '@material-ui/core';

/**
 * @return {string}
 */
function FormatTime(props) {
    return props.time.toLocaleString();
}

class Clock extends Component {

    constructor(props) {
        super(props);
        this.state = {date: new Date()};
    }

    componentDidMount() {
        this.timerID = setInterval(
            () => this.updateTime(), 1000
        );
    }

    updateTime() {
        this.setState(
            {date: new Date()}
        );
    }

    componentWillMount() {
        clearInterval(this.timerID);
    }


    render() {
        return (
            <div>
                现在时间:<FormatTime time={this.state.date}/>
            </div>
        );
    }
}

function App() {
    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo"/>
                <Button variant={"contain"} color={"primary"}>
                    你好,世界
                </Button>
                <Clock/>
            </header>
        </div>
    );
}
export default App;