state状态还是可以理解为Android,ios中一个类的成员变量,而props和state的区别是,props一经指定,就不能
修改,而state是可以修改的。一般来讲,你需要在constructor中初始化state,然后在需要修改时调用setState方法。
下面是一个闪烁文字的例子。
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