有两种类型的数据控制组件:props和state。props被父类设置,他们在组件的生命周期是固定的。要改变的数据,我们必须使用state。
一般来说,应该在构造函数中初始化state ,然后调用setState 改变它。
例如,假设我们想要文本闪烁。一旦当闪烁的组件被创建文本本身被设置,所以文本本身是一个prop。“文本是否打开或关闭“随着时间的推移改变,所以应该保存在state。
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
class Blink extends Component {
constructor(props) {
super(props);
this.state = {showText: true};
// Toggle the state every second
setInterval(() => {
this.setState({ showText: !this.state.showText });
}, 1000);
}
render() {
let display = this.state.showText ? this.props.text : ' ';
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);
在真实的应用程序中,您可能不会用计时器设置state。你可能当你有新的数据到从服务器,或从用户输入,设置状态。您还可以使用state容器像Redux控制你的数据流。在这种情况下你会使用Redux来修改您的state,而不是直接调用setState 。
State工作就像他在React一样,想了解更多细节处理State,您可以看看 React.Component API.
此时,你可能会生气,到目前为止,我们的大多数示例使用无聊默认黑色文本。为了让他更漂亮,你需要学习Style。
关注公众号:
更多精彩文章等你来!!!
[1]:参考文献 http://facebook.github.io/react-native/docs/state.html