在本机反应中倒数计时器

时间:2018-12-31 09:24:01

标签: react-native

我想以小时数显示倒计时:分钟:秒格式的本地反应。

我只想在本机反应中使用自定义倒数计时器,这样任何人都可以帮助我。

1 个答案:

答案 0 :(得分:3)

是的,我已经找到了解决方案,下面是我的完整代码

import React, { Component } from 'react';
import {
    View,
    Text,
    FlatList,
    TouchableOpacity,
    TouchableHighlight,
    Image
} from 'react-native';
import PropTypes from 'prop-types';
class CountDownTimer extends Component {

  constructor() {
    super();
    this.state = { time: {}, seconds: 3660 };
    this.timer = 0;
    this.startTimer = this.startTimer.bind(this);
    this.countDown = this.countDown.bind(this);
  }
  secondsToTime(secs){
    let hours = Math.floor(secs / (60 * 60));

    let divisor_for_minutes = secs % (60 * 60);
    let minutes = Math.floor(divisor_for_minutes / 60);

    let divisor_for_seconds = divisor_for_minutes % 60;
    let seconds = Math.ceil(divisor_for_seconds);

    let obj = {
      "h": hours,
      "m": minutes,
      "s": seconds
    };
    return obj;
  }

  componentDidMount() {
    let timeLeftVar = this.secondsToTime(this.state.seconds);
    this.setState({ time: timeLeftVar });
  }

  startTimer() {
    if (this.timer == 0 && this.state.seconds > 0) {
      this.timer = setInterval(this.countDown, 1000);
    }
  }

  countDown() {
    // Remove one second, set state so a re-render happens.
    let seconds = this.state.seconds - 1;
    this.setState({
      time: this.secondsToTime(seconds),
      seconds: seconds,
    });

    // Check if we're at zero.
    if (seconds == 0) { 
      clearInterval(this.timer);
    }
  }

  addLeadingZeros(value) {
    value = String(value);
    while (value.length < 2) {
      value = '0' + value;
    }
    return value;
  }
    render(){
        //const countDown = this.state;
        return(
            <View style={{flex : 1, backgroundColor : 'yellow', justifyContent : 'center', alignItems : 'center'}}>
             <Text>h: {this.addLeadingZeros(this.state.time.h)} m: {this.addLeadingZeros(this.state.time.m)} s: {this.addLeadingZeros(this.state.time.s)}</Text>
             <TouchableOpacity onPress={()=> this.startTimer()}>
               <Text>Click</Text>
             </TouchableOpacity>

            </View>
        )
    }
}



export default CountDownTimer;