React Native学习(3)State(状态)
我们使用两种数据来控制一个组件:props和state。props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。
如下:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
class Blink extends Component {
constructor(props) {
super(props);
this.state = { isShowingText: true };
setInterval(() => {
this.setState(previousState => {
return { isShowingText: !previousState.isShowingText };
});
}, 500);
}
render() {
if (!this.state.isShowingText) {
return null;
}
return (
<Text>{this.props.text}</Text>
);
}
}
export default class MyApp extends Component {
render() {
return (
<View>
<Blink text='测试测试' />
<Blink text='测试测试测试测试测试测试' />
</View>
);
}
}
AppRegistry.registerComponent('MyApp', () => MyApp);
注意
- 每次调用setState时,BlinkApp 都会重新执行 render 方法重新渲染。
- State 的工作原理和 React.js 完全一致。
- 一切界面变化都是状态state变化。
- state的修改必须通过setState()方法。