天天看點

一個非常簡單的react native計時器demo一個非常簡單的react native計時器demo

一個非常簡單的react native計時器demo

因為最近在學習react native,是以自己也一邊學習,一邊記下自己的筆記。今天看到定時器,是以寫了一個簡單的計時器。      
定時器:      
  • setTimeout, clearTimeout
  • setInterval, clearInterval
  • setImmediate, clearImmediate
  • requestAnimationFrame, cancelAnimationFrame

這是官方的手冊上提供的,我用的是setIntelval,因為自己是學的前端,整個列子使用的是es6的文法。

下面是截圖:      
以下是代碼:      
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
 TextInput,
 TouchableOpacity
} from 'react-native';
export default class AnimateDemo extends Component {
  constructor(props){
    super(props);
    this.state={
      data:0
    }
    this._index=0;
    this._timer=null;
  }
  countTime(){
    this._timer=setInterval(()=>{this.setState({data:this._index--}); if(this.state.data<=0){
        this._timer && clearInterval(this._timer);
        alert("時間到了");
    }},1000);
  }
  stopTime(){
      this._timer && clearInterval(this._timer);
  }
  componentWillUnmount() {
    this._timer && clearInterval(this._timer);
  }
 render() {
    return (
        
    
          
     
      請選擇時長(s)
     
          
     
      {this.setState({data:txt});this._index=txt;}}>

          
     
          
     
            
      
       
              {this.state.data}
            
      
          
     
          
     
              
      
                  
       
        開始
       
                 
              
      
               
      
                  
       
        暫停
       
                 
              
      
          
     
        
    
    );
  }
}
const styles=StyleSheet.create({
  container:{
     flex:1,
    },
    btngroup:{
      flexDirection:'row',
      
      justifyContent:'space-around'
    },
    showTime:{
      height:100,
      alignItems:'center'
    },
    btn:{
      justifyContent:'center',
      width:60,
      height:40,
      backgroundColor:'#7ecfe8',
      alignItems:'center'

    },
    timeText:{
      color:'red',
      fontSize:22,
    }

})



AppRegistry.registerComponent('AnimateDemo', () => AnimateDemo);
           
下一篇: 求解魔法陣

繼續閱讀