React-Native实战开发采坑之旅—倒计时组件

React-Native实战开发采坑之旅—倒计时组件

猿掌柜
2017-12-28 / 0 评论 / 57 阅读 / 正在检测是否收录...

继续踩着坑,昨天看视频,里面的倒计时代码貌似不太好使,搜索了下结果

修正值或依然报错,遂放弃。搜索到了一个非常简单的倒计时组件。

代码如下:

/**
 * 简单倒计时组件
 * c'est-la-vie
 */

import React, {Component} from 'react';
import {
  View,
  Text
} from 'react-native';
export default class MyCountTime extends Component{
    constructor(props) {
        super(props);
        let timeLeft=this.props.timeLeft>0 ? this.props.timeLeft:5
        let width=this.props.width || 60
        let height=this.props.height || 32
        let color=this.props.color || '#fff'
        let fontSize=this.props.fontSize || 22
        let fontWeight=this.props.fontWeight || '600'
        let borderColor=this.props.borderColor || '#ee735c'
        let borderWidth=this.props.borderWidth || 1
        let borderRadius=this.props.borderRadius || 4
        let backgroundColor=this.props.backgroundColor || '#ee735c'

        this.afterEnd=this.props.afterEnd || this._afterEnd
        this.style=this.props.style || this.countTextStyle

        this.state={
            timeLeft:timeLeft
        }
        this.countTextStyle={
            textAlign:'center',
            color:color,
            fontSize:fontSize,
            fontWeight:fontWeight

        }
        this.countViewStyle={
          backgroundColor:backgroundColor,
          alignItems:'center',
          borderColor:borderColor,
          borderWidth:borderWidth,
          borderRadius:borderRadius,
          width:width,
          height:height
        }
    }
    countdownfn(timeLeft,callback){
      if(timeLeft>0){
          let that=this
          let interval=setInterval(function(){
              if(that.state.timeLeft<1){
                  clearInterval(interval)
                  callback()
              }else{
                let totalTime=that.state.timeLeft
                that.setState({
                    timeLeft:totalTime-1
                })
              }
          },1000)
      }
    }
    _afterEnd(){
        console.log('------------time over');
    }
    componentDidMount(){
        let time=this.state.timeLeft
        let afterEnd=this.afterEnd
        this.countdownfn(time,afterEnd)
    }
    render(){
        return (
            <View>
                <Text style={this.style}>{this.state.timeLeft}秒后重发</Text>
            </View>
        )
    }
}

然后在所需要的地方引用 MyCountTime  这个组件

limport MyCountTime from '../common/countdown';

使用方法为

<MyCountTime
          timeLeft={60}
          width={100}
          height={60}
          color={'#ff9900'}
          fontSize={24}
          fontWeight={'normal'}
          borderColor={'transparent'}
          borderWidth={1}
          borderRadius={2}
          let backgroundColor={'#ee735c'}
          afterEnd={this._endcount.bind(this)}
           style={styles.countdown}/>

其中timeLeft为设置秒数,afterEnd为倒计时结束之后的回调函数

可以自定义样式

怎么样,是不是非常简单。困扰了我大半天的时间,好了,分享结束,继续挖坑咯

0

评论 (0)

取消