React Native ToastView 工具类(适配Android 与IOS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/danfengw/article/details/80778029

1、ToastView

根据属性type来设置不同的Toast的样式

import React, {Component} from 'react';
import {
    StyleSheet
} from 'react-native';


import px2dp from "../utils/Px2Dp";
import Toast, {DURATION} from 'react-native-easy-toast';
import PropTypes from 'prop-types';

export default class ToastView extends Component<Props> {

    static defaultProps = {
        type: 'android'
    };

    static propTypes = {
        type: PropTypes.oneOf(['android', 'ios']).isRequired,
    };

    constructor(props) {
        super(props);
        this.state = {
            style: '',
        }
    }

    setStyle = (type) => {
        if ('ios' === type) {
            return styles.bg_ios;
        } else if ('android' === type) {
            return styles.bg_android;
        }
    }
    setFontStyle = (type) => {
        if ('ios' === type) {
            return styles.fontsize_ios;
        } else if ('android' === type) {
            return styles.fontsize_android;
        }
    }

    show = (text) => {
        this.refs.toast.show(text)
    };
    show = (text, duration) => {
        this.refs.toast.show(text, duration)
    };

    render() {
        const {type} = this.props;
        return (
            <Toast ref="toast"
                   style={this.setStyle(type)}
                   position={'center'}
                   textStyle={this.setFontStyle(type)}
            />

        );
    }
}

const styles = StyleSheet.create({
    bg_android: {
        backgroundColor: '#000000CC',
        alignItems: 'center',
        justifyContent: 'center',
    },
    bg_ios: {
        backgroundColor: 'white', width: px2dp(606), height: px2dp(102),
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: px2dp(8), shadowColor: 'black',
        shadowOpacity: 0.13,
        shadowRadius: px2dp(16),
        shadowOffset: {
            width: 0,
            height: 0,
        },
        elevation: 0
    },
    fontsize_android: {
        color: 'white',
        fontSize: px2dp(30),
        fontFamily: 'PingFangSC-Medium',opacity: 0.8,
    },
    fontsize_ios:{
        color: '#3D3D3D',
        fontSize: px2dp(30),
        fontFamily: 'PingFangSC-Medium', opacity: 0.8,
    }
});

2、使用

在render()方法的return的View中添加

 <ToastView
          ref='toast'
          type={Platform.OS}
        />

弹出

 this.refs.toast.show("密码修改失败,请重试!");

猜你喜欢

转载自blog.csdn.net/danfengw/article/details/80778029