TimerLable.js 2.5 KB
'use strict';

import React from 'react';
import Immutable, {Map} from 'immutable';
import YH_Image from '../../../common/components/YH_Image';
import TimerMixin from 'react-timer-mixin';

import ReactNative, {
    View,
    Text,
    Image,
    StyleSheet,
    Dimensions,
    TouchableOpacity,
    Platform,
} from 'react-native';


export default class TimerLable extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
      		leftTime: this.props.leftTime,
        }
    }

    componentDidMount() {
      this.startTimer();
    }

    componentWillUnmount() {
        this.stopTimer();
    }

    startTimer() {
      this.stopTimer();
      if(this.state.leftTime > 0){
        this.timer = TimerMixin.setInterval(() => {
          let leftTime = this.state.leftTime-1;
          if (leftTime < 0) {
            this.props.onStop && this.props.onStop()
            this.stopTimer();
          }
          this.setState({
              leftTime,
          });
        }, 1000);
      }else {
        this.setState({
            leftTime: 0,
        });
      }
    }

    stopTimer() {
      console.log('stopTimer');
      this.timer && TimerMixin.clearTimeout(this.timer);
    }

    format(m) {
      if (m < 10){
        return 0+''+m;
      }
      return m+'';
    }

    formatTime(shijianchuo) {
      // 秒数
      var second = Math.floor(shijianchuo);
      // 小时位
      var hr = Math.floor(second / 3600);
      var hrFormat = this.format(hr);

      // 分钟位
      var min = Math.floor((second - hr * 3600) / 60);
      var minFormat = this.format(min);

      // 秒位
      var sec = (second - hr * 3600 - min * 60);
      var secFormat = this.format(sec);

      return hrFormat + ':' + minFormat + ':' + secFormat;
    }

    render() {
      if(this.state.leftTime > 0){
        return (
             <View style={styles.container}>
               <Text style={[styles.time,this.props.style ? this.props.style : {}]}>
                 {this.formatTime(this.state.leftTime)}
               </Text>
             </View>
          );
      } else {
        return null;
      }
    }
}

let {width, height} = Dimensions.get('window');
const DEVICE_WIDTH_RATIO = width / 375;
let leftOffset = 20 * DEVICE_WIDTH_RATIO;

let styles = StyleSheet.create({
    container: {
      flexDirection: 'row',
      alignItems: 'center',
    },
    time: {
      fontFamily: 'PingFang-SC-Medium',
      fontSize: 12,
      color: '#ffffff',
      letterSpacing: 0,
      marginLeft: 5,
    },
});