/** * Toast * Created by chenyxi on 2020/3/17. */ import React,{Component}from 'react'; import { StyleSheet, View, Easing, Dimensions, Text, Animated, ActivityIndicator, Keyboard, Platform } from 'react-native'; import PropTypes from 'prop-types'; const {width,height} = Dimensions.get('window'); //iphoneX const X_WIDTH = 375; const X_HEIGHT = 812; //显示时长 const DURATION = 1500; // Toast提示框透明度 const OPACITY = 0.8; class ToastView extends Component { static PropTypes = { message : PropTypes.string, time: PropTypes.number, isShow:PropTypes.bool, toastStartPosition:PropTypes.string, marginBottom:PropTypes.number, containerTop:PropTypes.number } dismissHandler = null; isShow = false; constructor(props) { super(props); this.state = { message:'', time:DURATION, isShow:false, toastStartPosition:'center',//toast展示的位置,默认中间位置 opacityAnimate: new Animated.Value(OPACITY), // 动画 值初始化 marginBottom:0,//距离底部高度 containerTop:0//距离顶部偏移 } } componentWillUnmount() { //在页面生命周期结束时,解除定时器,避免内存泄露 clearTimeout(this.dismissHandler); } show(message, position = 'center') { if(this.isShow){ clearTimeout(this.dismissHandler); this.state.isShow = false; } this.isShow = true; this.state.toastStartPosition = 'center'; this.state.marginBottom = 0; this.state.containerTop = 0; this.setState({ isShow:true, message:message }); this.state.opacityAnimate.setValue(OPACITY); this.state.isShow =true; if (this.dismissHandler) { clearTimeout(this.dismissHandler); } this.dismissHandler = setTimeout(() => { // 开启动画 Animated.timing(this.state.opacityAnimate, { toValue: 0.0, duration: 600, }).start(() => { // 动画结束后,初始化状态 this.setState({ isShow: false, }); this.isShow = false; this.onDismiss(); }); }, this.state.time); } onDismiss = () => { if (this.props.onDismiss) { this.props.onDismiss() } } //判断是否iphoneX isIphoneX = () => { return ( Platform.OS === 'ios' && ((height === X_HEIGHT && width === X_WIDTH) || (height === X_WIDTH && width === X_HEIGHT)) ) } render() { return this.state.isShow ?( {/*pointerEvents='none'*/} {this.state.message} ):null } } const styles = StyleSheet.create({ textContainer: { backgroundColor: 'rgba(0,0,0,.8)', borderRadius: 8, padding: 10, maxWidth: width/5*4, justifyContent: 'center', alignItems: 'center', }, defaultText: { color: "#FFF", fontSize: 15, }, container: { position: "absolute", width: width, height: height, zIndex: 99999, flexDirection: "row", justifyContent: "center", alignItems: 'center', } }); export default ToastView