react 簡單倒計時

倒計時組件react

import React, { Component } from 'react'

export default class countDown extends Component {
    constructor(props) {
        super(props)
        this.state = {
            second: this.props.value
        }
    }
    componentDidMount () {
        this.countDown()
    }
    componentWillUnmount () {
        if (this.timmerId) clearInterval(this.timmerId)
    }
    componentDidUpdate (preProps) {
        if (preProps.value !== this.props.value) {
            if (this.timmerId) clearInterval(this.timmerId)
            this.setState({
                second: this.props.value
            }, () => {
                this.countDown()
            })
        }
    }
    countDown = () => {
        this.timmerId = setInterval(() => {
            this.setState({
                second: this.state.second - 1
            }, () => {
                if (this.state.second <= 0) {
                    clearInterval(this.timmerId)
                }
            })
        }, 1000)
    }
    render() {
        return (
            <div>
                {this.state.second}
            </div>
        )
    }
}

須要手動更新時
1.手動更新key組件從新渲染this

<CountDown key={this.state.key} value={this.state.value}/>

2.應該能夠使用ref,操做~~~code

相關文章
相關標籤/搜索