下面是一個閃爍文字的例子。
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
class Blink extends Component {
constructor(props) {
//哈哈,終於看到大家熟悉的構造函數了
super(props);
this.state = { showText: true };
// 每1000毫秒對showText狀態做一次取反操作
setInterval(() => {
this.setState({ showText: !this.state.showText });
}, 1000);
}
render() {
// 根據當前showText的值決定是否顯示text內容
let display = this.state.showText ? this.props.text : ' ';
//這就是大家熟悉的問號表達式,當狀態showText爲真時,
//設置爲text。否者爲空.而showText被上面setInterval所控制
return (
<Text>{display}</Text>
);
}
}
class BlinkApp extends Component {
render() {
return (
<View>
<Blink text='I love to blink' />
<Blink text='Yes blinking is so great' />
<Blink text='Why did they ever take this out of HTML' />
<Blink text='Look at me look at me look at me' />
</View>
);
}
}
AppRegistry.registerComponent('BlinkApp', () => BlinkApp);
更多內容參看:http://reactnative.cn/docs/0.31/state.html