新建js文件:
import React, { Component } from 'react';
import { StyleSheet, Animated, Text, View, Modal, Easing } from 'react-native';
import UiUtils from '../UiUtils';
let utils = new UiUtils();
utils.setHeightCalculateEnable(2224);
const getDeviceValue = utils.getDeviceValue;
const DEFAULT_SHOW_TIME = 2000;
const DEFAULT_FADE_IN_OPACITY_VALUE = new Animated.Value(1);
class Toast extends Component {
constructor(props) {
super(props);
this.state = {
isShowToast: false,
msg: '',
fadeInOpacity: DEFAULT_FADE_IN_OPACITY_VALUE,
};
}
getInitialState() {
return { fadeInOpacity: DEFAULT_FADE_IN_OPACITY_VALUE };
}
show = (msg, showTime) => {
if (this.state.isShowToast === true) {
return;
}
let toastShowTime = showTime ? showTime : DEFAULT_SHOW_TIME;
setTimeout(() => {
this.hidden();
}, toastShowTime);
this.setState({
isShowToast: true,
msg: msg,
});
};
showAnimation = (msg, showTime) => {
if (this.state.isShowToast === true) {
return;
}
let animatedDuration = showTime ? showTime : DEFAULT_SHOW_TIME;
let timing = Animated.timing(this.state.fadeInOpacity, {
toValue: 0,
duration: animatedDuration,
easing: Easing.linear,
useNativeDriver: false,
});
timing.start((isFinished) => {
if (isFinished) {
this.hidden();
timing.reset();
}
});
this.setState({
isShowToast: true,
msg: msg,
fadeInOpacity: DEFAULT_FADE_IN_OPACITY_VALUE,
});
};
hidden = () => {
this.setState({
isShowToast: false,
msg: '',
});
};
render() {
return (
<Modal
//无效
pointerEvents="none"
animationType="fade"
transparent={true}
visible={this.state.isShowToast}
>
<Animated.View
ref={(ref) => (this.animatedView = ref)}
style={[styles.mainContainer, { opacity: this.state.fadeInOpacity }]}
>
<View style={styles.msgContainer}>
<Text style={styles.msg}>{this.state.msg}</Text>
</View>
</Animated.View>
</Modal>
);
}
}
export default Toast;
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
alignSelf: 'stretch',
justifyContent: 'flex-end',
},
msgContainer: {
alignContent: 'center',
justifyContent: 'center',
alignSelf: 'center',
marginBottom: getDeviceValue(350),
},
msg: {
padding: getDeviceValue(30),
borderRadius: getDeviceValue(30),
backgroundColor: 'black',
textAlign: 'center',
fontSize: getDeviceValue(60),
color: 'white',
},
});
使用:
this.toast.show('这是哈哈哈哈哈');
....
<Toast ref={(ref) => (this.toast = ref)} />
.....