定时器

setTimeout和clearTimeout基本用法

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Navigator,
  Image,
  TouchableHighlight,
  ScrollView,
  Animated
} from 'react-native';

import MyScene from './MyScene';

export default class DTest extends Component {

  constructor(props) {
      super(props);  
      this.state={
      }
  }
  componentDidMount() {
    this.timer = setTimeout(
      () => {
        this.setState({content:'我是定时器打印的内容...One'})
      },
      5000
    );
    this.timer_two = setTimeout(
      () => {
        this.setState({msg:'我是定时器打印的内容...Two'})
      },
      1000
    );
  }
  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
    this.timer_two && clearTimeout(this.timer_two);
  }
  render() {
    return (
      
        
           定时器实例
        
        {this.state.content}
        {this.state.msg}
      
    );
  }
}

const styles = StyleSheet.create({
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

// 注册应用(registerComponent)后才能正确渲染
// 注意:只把应用作为一个整体注册一次,而不是每个组件/模块都注册
AppRegistry.registerComponent('DTest', () => DTest);
定时器_第1张图片

setInterval和clearInterval基本用法

index.ios.js:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Navigator,
  Image,
  TouchableHighlight,
  ScrollView,
  Animated
} from 'react-native';

import MyScene from './MyScene';

export default class DTest extends Component {

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

  render() {
    return (
      
        {
            this.interval=setInterval(() => {this.setState({sum:(this.state.sum+1)});
          },400);
        }}/> 
        {this.state.sum}
        {
          this.interval && clearInterval(this.interval)
        }}/>
          
    );
  }
}


const styles = StyleSheet.create({
  welcome: {
    flex:1,
    alignItems:"center"
  },
});
// 注册应用(registerComponent)后才能正确渲染
// 注意:只把应用作为一个整体注册一次,而不是每个组件/模块都注册
AppRegistry.registerComponent('DTest', () => DTest);

MyScene.js:

import React, { Component, PropTypes } from 'react';
import { View, Text, TouchableHighlight } from 'react-native';

export default class MyScene extends Component {
 
  render() {
    return (
      
        
          { this.props.text }
           
      
    )
  }
}

效果图:


定时器_第2张图片

你可能感兴趣的:(定时器)