一個組件被兩種數(shù)據(jù)控制:props和state。props由其父類設(shè)置,并且在這個組件的生命周期內(nèi)胧华,他們都是被鎖定的。對于要改變的數(shù)據(jù)宙彪,我們必須要使用state矩动。
一般情況下,你應(yīng)該在構(gòu)造函數(shù)中初始化state释漆,然后當(dāng)你想要改變它的時候悲没,調(diào)用setState。
舉例來說男图,我們想要做一個text示姿,這個text每時每刻都在閃爍,在創(chuàng)建閃爍組件的時候把text設(shè)置一次享言,所以text本身就是一個prop峻凫,“text目前是開啟的還是關(guān)閉的”隨著時間而改變,這個數(shù)據(jù)應(yīng)保存在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);
在實際應(yīng)用中荧琼,你可能不會用一個計時器來設(shè)置state。你也許會在你從服務(wù)器獲取到數(shù)據(jù)差牛,或從用戶輸入獲取數(shù)據(jù)時設(shè)置state命锄;您還可以使用像Redux的state容器來控制你的數(shù)據(jù)流,在這種情況下偏化,你可以使用Redux來修改你的state脐恩,而不是直接調(diào)用setState。
State的作用跟在React中一樣侦讨,想要掌握更多關(guān)于state的詳細(xì)信息驶冒,你可以看看React.Component API苟翻。
在這一點上,你可能會惱火骗污,我們的大多數(shù)例子使用至今都是默認(rèn)的無聊的黑色text崇猫。為了讓界面變得更漂亮,你將不得不學(xué)習(xí)Style需忿。