React—计时器(每秒数字增加1)

import React from 'react';
import ReactDom from 'react-dom';
let number = 0;
class Clock extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            num: 0
        }
    }
    componentDidMount() { // 生命周期
        this.timerID = setInterval(
            () => {
                number = number +1
                this.tick(number);
            },
            1000
        );
    }

    componentWillUnmount() { // 生命周期
        clearInterval(this.timerID);
    }

    tick(number) {
        this.setState({
            num: number
        });
    }
    render () {
        return (
            

Hello, world!

现在是 {this.state.num}

); } } ReactDom.render(
, document.getElementById('root') )

你可能感兴趣的:(React)