React-Native 封装轻量级loading页面加载等待
2018-08-31 本文已影响11人
云深不知处a
先看效果
QQ20180831-162138-HD.gif
直接贴上代码
/**
*Created by macping
*Date:2018/8/28
*/
/**
* 使用案例
<PopLoading ref='cover'/>
this.refs.cover && this.refs.cover.showCover();
this.refs.cover && this.refs.cover.dismissCover();
*/
'use strict';
import React, {Component} from 'react';
import {
StyleSheet,
Modal,
Animated,
ImageBackground,
Image,
Easing,
TouchableOpacity
} from 'react-native';
const imgWidth = (70 * 0.8);
const imgHeight = 110 * imgWidth / 70;
export default class PopLoading extends Component {
constructor(props) {
super(props);
this.state = {
isShow: false,
imgAnimated: new Animated.Value(0),
}
}
/**
* defineMethod
*/
loadingImgAnimated = () => {
this.state.imgAnimated.setValue(0);
Animated.timing(this.state.imgAnimated, {
toValue: imgWidth,
duration: 2500,
easing: Easing.linear
// delay:200,
}).start(() => {
this.startTimer();
// this.loadingImgAnimated();
});
}
//显示
dismissCover = () => {
this.setState({
isShow: false
})
this.stopImgAnimated();
}
//消失
showCover = () => {
this.setState({
isShow: true,
})
this.startTimer();
}
// 为了可关闭动画,使用定时器更容易管理
startTimer = () => {
this.stopImgAnimated();
this.timer = setTimeout(() => {
this.loadingImgAnimated();
}, 200);
}
// 重置动画
stopImgAnimated = () => {
this.state.imgAnimated.setValue(0);
this.state.imgAnimated.stopAnimation();
this.timer && clearTimeout(this.timer);
}
/**
* render
*/
render() {
if (!this.state.isShow) {
return null;
} else {
return (
<Modal
style={styles.container}
transparent={true}
visible={this.state.isShow}
animationType={'fade'}
onRequestClose={() => {
//关闭
}}
>
{this.renderCover()}
</Modal>
)
}
}
//蒙版背景
renderCover() {
return (
<TouchableOpacity
style={styles.container}
activeOpacity={1.0}
onPress={() => {
}}
>
<ImageBackground
source={require('./ImageSrc/Loading/logo_grey.png')}
style={styles.bgImg}
>
<Animated.View
style={[styles.image, {
width: this.state.imgAnimated,
backgroundColor: 'transparent',
overflow: 'hidden'
}]}
>
<Image
source={require('./ImageSrc/Loading/logo_color.png')}
style={styles.bgImg}
resizeMode={'cover'}
/>
</Animated.View>
</ImageBackground>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.4)',
justifyContent: 'center',
alignItems: 'center',
},
bgImg: {
width: imgWidth,
height: imgHeight,
}
});