網(wǎng)絡(luò)請求等延時操作往往都會用到loading,遮罩在當前頁面寥院,react natvie自帶的loading組件ActivityIndicator往往不能滿足需求,我們就需要自定義loading組件了涛目。
因為loading是個很簡單的功能,沒必要去安裝一個組件凛澎,主要通過Modal和ActivityIndicator實現(xiàn)霹肝。
Loading.js
'use strict';
import React from 'react';
import PropTypes from 'prop-types'
import {StyleSheet, Text, View, Modal, ActivityIndicator} from 'react-native';
let lo;
const defaultTimeOut = -1;//設(shè)置顯示時間標識
export class EasyLoading {
/**
* 顯示Loading
* @param text Loading顯示文本,默認為'加載中'
* @param timeout Loading顯示時間塑煎,為-1時會一只顯示沫换,需要手動關(guān)閉
*/
static show(text = '加載中...', timeout = defaultTimeOut) {
console.log(timeout);
lo.setState({"isShow": true, "text": text, "timeout": timeout});
}
/**
* 關(guān)閉Loading
*/
static dismiss() {
lo.setState({"isShow": false});
}
}
export class Loading extends React.Component {
static propTypes = {
color: PropTypes.string,
textStyle: PropTypes.any,
loadingStyle: PropTypes.any,
};
constructor(props) {
super(props);
this.handle = 0;
this.state = {
isShow: false,
timeout: defaultTimeOut,
text: "加載中..."
};
lo = this;
}
componentWillUnmount() {
clearTimeout(this.handle);
}
render() {
clearTimeout(this.handle);
(this.state.timeout !== defaultTimeOut) && (this.handle = setTimeout(() => {
EasyLoading.dismiss();
}, this.state.timeout));
return (
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.isShow}
onRequestClose={() => {
alert("Modal has been closed.")
}}>
<View style={styles.container}>
<View style={[styles.load_box, this.props.loadingStyle]}>
<ActivityIndicator animating={true} color={this.props.color || '#FFF'} size={'large'}
style={styles.load_progress}/>
<Text style={[styles.load_text, this.props.textStyle]}>{this.state.text}</Text>
</View>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
load_box: {
width: 100,
height: 100,
backgroundColor: '#000',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 10
},
load_progress: {
width: 50,
height: 50
},
//默認字體顏色
load_text: {
color: '#FFF',
},
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(178,178,178,0.8)',
},
});
使用
//引入組件,"../custom/EasyLoading"為EasyLoading.js文件存放的路徑
import {EasyLoading, Loading} from "../custom/EasyLoading";
_showLoading() {
//EasyLoading.show();//顯示
//EasyLoading.dimiss();//關(guān)閉
//自定義文本和超時時間
EasyLoading.show('加載中...', 2000);
}
render() {
return (<View style={styles.container}>
<Button title={'show loading'} onPress={() => this._showLoading()}>
<Loading/>
</View>
);
}
自定義樣式
<Loading color={'red'} loadingStyle={{backgroundColor: 'lightgreen'}} textStyle={{color: 'red', fontSize: 18}}/>