我們使用兩種數(shù)據(jù)來(lái)控制一個(gè)組件:props和state。props是在父組件中指定,而且一經(jīng)指定,在被指定的組件的生命周期中則不再改變。 對(duì)于需要改變的數(shù)據(jù),我們需要使用state。
一般來(lái)說(shuō),你需要在constructor中初始化state(譯注:這是ES6的寫(xiě)法,早期的很多ES5的例子使用的是getInitialState方法來(lái)初始化state,這一做法會(huì)逐漸被淘汰),然后在需要修改時(shí)調(diào)用setState方法。
假如我們需要制作一段不停閃爍的文字。文字內(nèi)容本身在組件創(chuàng)建時(shí)就已經(jīng)指定好了,所以文字內(nèi)容應(yīng)該是一個(gè)prop。而文字的顯示或隱藏的狀態(tài)(快速的顯隱切換就產(chǎn)生了閃爍的效果)則是隨著時(shí)間變化的,因此這一狀態(tài)應(yīng)該寫(xiě)到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 };
// 每1000毫秒對(duì)showText狀態(tài)做一次取反操作
setInterval(() => {
this.setState({ showText: !this.state.showText });
}, 1000);
}
render() {
// 根據(jù)當(dāng)前showText的值決定是否顯示text內(nèi)容
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);
實(shí)際開(kāi)發(fā)中,我們一般不會(huì)在定時(shí)器函數(shù)(setInterval、setTimeout等)中來(lái)操作state。典型的場(chǎng)景是在接收到服務(wù)器返回的新數(shù)據(jù),或者在用戶輸入數(shù)據(jù)之后。你也可以使用一些“狀態(tài)容器”比如Redux來(lái)統(tǒng)一管理數(shù)據(jù)流(但我們不建議新手過(guò)早去學(xué)習(xí)redux)。