這里講一下React Native中的一個(gè)組件——ActivityIndicator,這是一個(gè)加載指示器,俗稱菊花,很常見的,效果如下所示:

可以看到圖中有兩個(gè)加載指示器,一大一小,這是尺寸不是我設(shè)置的,這個(gè)組件本身就有一個(gè)屬性是設(shè)置其大小的,兩個(gè)選項(xiàng),一大一小。這里順便就介紹一些該組件的屬性:
- animating:這個(gè)參數(shù)接受布爾型的值,表示是否顯示加載指示器。
- color:string型參數(shù),用來設(shè)置指示器的顏色,默認(rèn)是灰色的,我們一般也不管他。
- hidesWhenStopped(僅iOS可用):在沒有動(dòng)畫的時(shí)候,是否要隱藏指示器(默認(rèn)為true)。
- size:這就是設(shè)置尺寸的,就兩個(gè)選項(xiàng),small和large,一小一大。
能設(shè)置的就這幾個(gè)參數(shù),接下來我們看看這個(gè)例子。例子中有一個(gè)按鈕,控制了指示器的顯示和隱藏。按鈕我們用TouchableOpacity組件來實(shí)現(xiàn),這個(gè)組件可以添加一個(gè)響應(yīng)方法,下面我們放一小一大兩個(gè)指示器,代碼如下:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ActivityIndicator,
TouchableOpacity
} from 'react-native';
class RNActivityIndicatorDemo extends Component {
constructor(props) {
super(props);
this.state = {// 初始設(shè)為顯示加載動(dòng)畫
animating: true,
};
}
// 按鈕響應(yīng)方法,切換顯示與隱藏
showOrHide() {
if (this.state.animating) {
this.setState({
animating: false
});
} else {
this.setState({
animating: true
});
}
}
render() {
return (
<View style={styles.container}>
{/* 切換顯示或隱藏的按鈕 */}
<TouchableOpacity underlayColor="#fff" style={styles.btn} onPress={
this.showOrHide.bind(this)}>
<Text style={{color:'#fff', fontSize: 20}}>顯示/隱藏</Text>
</TouchableOpacity>
{/* 小號(hào)的指示器 */}
<ActivityIndicator
animating={this.state.animating}
style={[styles.centering, {height: 80}]}
size="small" />
{/* 大號(hào)的指示器 */}
<ActivityIndicator
animating={this.state.animating}
style={[styles.centering, {height: 80}]}
size="large" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
centering: {
alignItems: 'center',
justifyContent: 'center',
padding: 8,
},
btn:{
marginTop:10,
width:150,
height:35,
backgroundColor:'#3BC1FF',
justifyContent:'center',
alignItems:'center',
borderRadius:4,
},
});
AppRegistry.registerComponent('RNActivityIndicatorDemo', () => RNActivityIndicatorDemo);
看代碼,我們首先就在state中加了一個(gè)變量animating,用來控制指示器的顯示與隱藏,初始是顯示的。然后看我們的界面元素部分,即render中的部分,除了最外面一層view外,最上面就是一個(gè)TouchableOpacity,onPress屬性指向了一個(gè)響應(yīng)方法,即showOrHide方法,在這個(gè)方法中我們可以看到,很簡(jiǎn)單地實(shí)現(xiàn)了一個(gè)通過animating變量切換顯示與隱藏的功能。因此下面的ActivityIndicator元素中我們的animating屬性是用state中的animating變量來控制的,其余的屬性我們基本是默認(rèn)的,size一小一大,很簡(jiǎn)單的例子。
這里可以下載我的示例工程:https://github.com/Cloudox/RNActivityIndicatorDemo