React Native ToastView 工具类适配Android 与IOS

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),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',}
});

2、使用

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

<ToastView
          ref='toast'
          type={(Platform.OS === 'ios' ? 'ios' : 'android')}
        />

弹出

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

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...