我們使用兩種數(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中。
創(chuàng)建Blink組件,新建一個(gè)blink.js文件
class Blink extends Component {
// 需要在constructor中初始化state,這是ES6的語(yǔ)法,之前使用的是getInitialState方法來(lái)初始化state
// 這一做法將會(huì)逐漸被淘汰,在需要修改的地方調(diào)用setState方法即可
constructor(props) {
super(props);
this.state = {showText: true};
// 每1000毫秒對(duì)showText狀態(tài)取一次反操作
setInterval(() => {
this.setState(partialState => {
return {showText: !partialState.showText};
});
}, 1000);
}
render() {
// 根據(jù)當(dāng)前的showText的值的情況來(lái)決定是否顯示text內(nèi)容
let display = this.state.showText ? this.props.text : " ";
return (
<Text>{display}</Text>
);
}
}
module.exports = Blink;
在index.ios.js中引入Blink組件
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
var Blink = require("./blink.js");
class Demo extends Component {
render() {
return (
<View style={{marginTop: 50, alignItems: "center"}}>
<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('Demo', () => Demo);
執(zhí)行效果如下:
運(yùn)行結(jié)果.gif