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 (
<View style={{margin:20}}>
<Text style={styles.welcome}>
定时器实例
</Text>
<Text>{this.state.content}</Text>
<Text>{this.state.msg}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
// 注册应用(registerComponent)后才能正确渲染
// 注意:只把应用作为一个整体注册一次,而不是每个组件/模块都注册
AppRegistry.registerComponent('DTest', () => DTest);
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 (
<View style={styles.welcome}>
<MyScene text='测试setInterval'
onPress={()=>{
this.interval=setInterval(() => {this.setState({sum:(this.state.sum+1)});
},400);
}}/>
<Text>{this.state.sum}</Text>
<MyScene text='测试setInterval'
onPress={()=>{
this.interval && clearInterval(this.interval)
}}/>
</View>
);
}
}
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 (
<View style={{flex:1, justifyContent:"center", alignItems:"center"}}>
<TouchableHighlight onPress={this.props.onPress}>
<Text>{ this.props.text }</Text>
</TouchableHighlight>
</View>
)
}
}
效果图:
网友评论