反应计时器组件百分比

时间:2020-05-13 03:45:19

标签: javascript reactjs timer

我正在使反应中的计时器组件显示圆形进度栏中剩余的时间百分比。计时器工作正常,但百分比未正常工作。我尝试在线搜索以计算时间百分比,但没有得到有效的示例。计时器的代码在这里

import React, { Component } from 'react';

class TimerCSS extends Component {

    constructor(props){
        super(props);

        this.state = {
            hours: 2,
            min: 0,
            secs: 0,
            fin: false,
            percent: 100
        }
    }

    componentDidMount(){
        this.myInterval = setInterval(() => {
            var {hours,min,secs,fin,percent} = this.state;

            if(secs > 0){
                secs--;
            } else {
                secs = 59;
                if(min > 0){
                    min--;
                } else {
                    min = 59;
                    hours--;
                    if(hours < 0){
                        fin = true;
                        hours = min = secs = 0;
                    }
                }
            }

            this.setState(prevState => ({
                hours, min , secs , fin, percent: Math.round(prevState.percent - 0.83)
            }))
        }, 100);
    }

    componentDidUpdate(){

    }


    render() {
        const {hours,min,secs,fin,percent} = this.state;
        console.log(percent);
        if(fin){
            return(
                <div>
                <center>Finished</center>
            </div>
            )
        } else {
        return (

              <div className={`c100 p${percent}`}>
                <span>1:59</span>
                <div className="slice">
                  <div className="bar"></div>
                  <div className="fill"></div>
                </div>
              </div>

        );
        }
    }
}

export default TimerCSS;

循环进度已下载,并且仅基于CSS。

1 个答案:

答案 0 :(得分:1)

您需要以秒为单位(2 * 60 * 60),以秒为单位的初始时间(2小时,如果我理解的话),因此:

this.state = {
  initialTime: 7200,
  hours: 2,
  min: 0,
  secs: 0,
  fin: false,
  percent: 100
}

然后,您需要以秒为单位的currentTime引用,因此请在间隔内的setState之前:

var currentTime = (hours * 60 * 60) + (min * 60) + secs;

最终您可以得到百分比,所以:

var percentage = currentTime / this.state.initialTime * 100;