React Native 封装Toast

前言

使用react native的小伙伴都知道,官方并未提供轻提示组件,只提供了ToastAndroid API,顾名思义,只能再安卓环境下使用,对于ios就爱莫能助,故此,只能通过官方的核心组件,自行封装,实现Toast功能

实现

创建文件

首先我们需要创建一个Toast组件,引入对应需要的依赖,icon等等

声明数据类型,通用方法

import React, {Component} from 'react';
import {View, Text, StyleSheet, Animated, Easing} from 'react-native';
import icon_success from '../assets/images/icon-success.png';
import icon_error from '../assets/images/icon-error.png';
import icon_loading from '../assets/images/icon-loading.png';
import icon_warning from '../assets/images/icon-warning.png'; type StateType = {
isVisible: boolean;
icon: any;
message: string;
}; type ParamsType = string | {message: string; duration?: number};
function getParams(data: ParamsType): {message: string; duration: number} {
let msg!: string;
let dur!: number;
if (typeof data === 'string') {
msg = data;
dur = 2000;
} else {
msg = data.message;
dur = data.duration != null ? data.duration : 2000;
}
return {
message: msg,
duration: dur,
};
}

实现样式和UI层次渲染

我们需要创建一个class,接收参数,并根据不同的条件渲染:success、error、warning、show、loading等

并抛出自己的实例

class ToastComponent extends Component<{} | Readonly<{}>, StateType> {
timeout!: NodeJS.Timeout;
rotate: Animated.Value = new Animated.Value(0);
constructor(props: {} | Readonly<{}>) {
super(props);
this.state = {
isVisible: false,
icon: null,
message: '',
};
Toast.setToastInstance(this);
}
showToast(icon: any, message: string, duration: number) {
this.setState({
isVisible: true,
icon,
message,
});
if (duration !== 0) {
const timeout = setTimeout(() => {
this.closeToast();
}, duration);
this.timeout = timeout;
}
}
showRotate() {
Animated.loop(
Animated.timing(this.rotate, {
toValue: 360,
duration: 1000,
easing: Easing.linear,
useNativeDriver: true,
}),
).start();
}
closeToast() {
this.setState({
isVisible: false,
icon: null,
message: '',
});
if (this.timeout) {
clearTimeout(this.timeout);
}
} render() {
const {isVisible, icon, message} = this.state;
return isVisible ? (
<View style={style.root}>
<View style={[style.main, icon === null ? null : style.mainShowStyle]}>
{icon && (
<Animated.Image
style={[
style.icon,
{
transform: [
{
rotate: this.rotate.interpolate({
inputRange: [0, 360],
outputRange: ['0deg', '360deg'],
}),
},
],
},
]}
source={icon}
/>
)}
<Text style={style.tip}>{message}</Text>
</View>
</View>
) : null;
}
} const style = StyleSheet.create({
root: {
height: '100%',
backgroundColor: 'transparent',
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 99999,
alignItems: 'center',
justifyContent: 'center',
},
main: {
maxWidth: 200,
maxHeight: 200,
backgroundColor: '#00000099',
borderRadius: 8,
alignItems: 'center',
justifyContent: 'center',
padding: 20,
},
mainShowStyle: {
minWidth: 140,
minHeight: 140,
},
icon: {
width: 36,
height: 36,
resizeMode: 'cover',
marginBottom: 20,
},
tip: {
fontSize: 14,
color: '#fff',
fontWeight: 'bold',
textAlign: 'center',
},
});

抛出对外调用的方法

此时我们需要再声明一个class,对外抛出方法以供调用

最后导出即可

class Toast extends Component<{} | Readonly<{}>, {} | Readonly<{}>> {
static toastInstance: ToastComponent;
static show(data: ParamsType) {
const {message, duration} = getParams(data);
this.toastInstance.showToast(null, message, duration);
}
static loading(data: ParamsType) {
const {message, duration} = getParams(data);
this.toastInstance.showToast(icon_loading, message, duration);
this.toastInstance.showRotate();
}
static success(data: ParamsType) {
const {message, duration} = getParams(data);
this.toastInstance.showToast(icon_success, message, duration);
}
static error(data: ParamsType) {
const {message, duration} = getParams(data);
this.toastInstance.showToast(icon_error, message, duration);
}
static warning(data: ParamsType) {
const {message, duration} = getParams(data);
this.toastInstance.showToast(icon_warning, message, duration);
}
static clear() {
if (this.toastInstance) {
this.toastInstance.closeToast();
}
}
static setToastInstance(toastInstance: ToastComponent) {
this.toastInstance = toastInstance;
}
render() {
return null;
}
}; export {Toast, ToastComponent};

组件挂载

我们需要将UI层组件在入口TSX文件进行挂载,不然Toast无法渲染

/* APP.tsx */
import React from 'react';
import {StatusBar} from 'react-native';
import {SafeAreaProvider} from 'react-native-safe-area-context'; import {ToastComponent} from './src/components/Toast'; const Stack = createStackNavigator(); function App(): JSX.Element {
return (
<SafeAreaProvider>
<StatusBar barStyle="dark-content" backgroundColor="#EAF7FF" />
<ToastComponent />
</SafeAreaProvider>
);
} export default App;

API调用

挂载完成,接下来,在我们需要用到的地方,调用即可

import {Toast} from '../../components/Toast';

//
Toast.success('登录成功');
Toast.error('密码错误');
Toast.warning('我是警告');
Toast.loading('加载中,请稍后');
Toast.loading({message: "我是不关闭的Toast", duration: 0})
Toast.success({message: "我是2秒后关闭的Toast", duration: 2000});
Toast.clear(); // 手动关闭

React Native实现Toast轻提示和loading的更多相关文章

  1. React Native封装Toast与加载Loading组件

    React Native开发封装Toast与加载Loading组件 在App开发中,我们避免不了使用的两个组件,一个Toast,一个网络加载Loading,在RN开发中,也是一样,React Nati ...

  2. React Native之通知栏消息提示(android)

    React Native之通知栏消息提示(android) 一,需求分析与概述 1.1,推送作为手机应用的基本功能,是手机应用的重要部分,如果自己实现一套推送系统费时费力,所以大部分的应用都会选择使用 ...

  3. React Native之通知栏消息提示(ios)

    React Native之通知栏消息提示(ios) 一,需求分析与概述 详情请查看:React Native之通知栏消息提示(android) 二,极光推送注册与集成 2.1,注册 详情请查看:Rea ...

  4. WebStorm开发工具设置React Native智能提示

    最近在做React Native开发的时候,相信大家一般会使用WebStorm,Sublime,Atom等等开发工具.二之前搞前端的对WebStorm会很熟悉,WebStorm最新版是WebStorm ...

  5. React native 开发工具 VSCode

    1.VSCODE下载地址:先下载VSCode软件 2.代码提示功能: 打开 VSCode ,然后 按住键盘 command+p,然后在vscode上面输入框 输入: "ext install ...

  6. Wait… What Happens When my React Native Application Starts? — An In-depth Look Inside React Native

    Discover how React Native functions internally, and what it does for you without you knowing it. Dis ...

  7. [react native] Error loading page

    如上图显示的错误,解决方法如下: 在react native ios项目的info.plist文件中,新增一个属性. 在Info.plist中添加NSAppTransportSecurity类型Dic ...

  8. React Native:使用 JavaScript 构建原生应用

    [转载] 本篇为联合翻译,译者:寸志,范洪春,kmokidd,姜天意 数月前,Facebook 对外宣布了正在开发的 React Native 框架,这个框架允许你使用 JavaScript 开发原生 ...

  9. react native 入门实践

    上周末开始接触react native,版本为0.37,边学边看写了个demo,语法使用es6/7和jsx.准备分享一下这个过程.之前没有native开发和react的使用经验,不对之处烦请指出.希望 ...

  10. iOS原生项目中集成React Native

    1.本文的前提条件是,电脑上已经安装了CocoaPods,React Native相关环境. 2.使用Xcode新建一个工程.EmbedRNMeituan [图1] 3.使用CocoaPods安装Re ...

随机推荐

  1. 【QCustomPlot】性能提升之修改源码(版本 V2.x.x)

    说明 使用 QCustomPlot 绘图库的过程中,有时候觉得原生的功能不太够用,比如它没有曲线平滑功能:有时候又觉得更新绘图数据时逐个赋值效率太低,如果能直接操作内存就好了:还有时候希望减轻 CPU ...

  2. [Docker] Docker之安装Nginx

    0 序言 略 1 安装步骤 Step1 下载镜像 搜素.下载镜像 https://hub.docker.com/_/nginx?tab=tags 这里选择官方镜像1.22.0版本 docker sea ...

  3. SpringBoot定义优雅全局统一Restful API 响应框架五

    闲话不多说,继续优化 全局统一Restful API 响应框架 做到项目通用 接口可扩展. 如果没有看前面几篇文章请先看前面几篇 SpringBoot定义优雅全局统一Restful API 响应框架 ...

  4. nodejs使用eggjs创建项目,接入influxdb完成单表增删改查

    转载请注明出处: 1.Eggjs 特性: Eggjs 是 Node.js 服务端应用开发框架,它提供了一套约定,使开发者能够快速搭建.开发和部署应用.以下是 Egg.js 的一些特性和作用: 框架内置 ...

  5. 【理论积累】Python中的Pandas库【一】

    Pandas库介绍 Pandas 是一个用于数据分析的 Python 第三方库,能够处理和分析不同格式的数据,例如:CSV.Excel.SQL 数据库等.Pandas 提供了两种数据结构,分别为 Se ...

  6. 2023-06-14:我们从二叉树的根节点 root 开始进行深度优先搜索。 在遍历中的每个节点处,我们输出 D 条短划线(其中 D 是该节点的深度) 然后输出该节点的值。(如果节点的深度为 D,则其

    2023-06-14:我们从二叉树的根节点 root 开始进行深度优先搜索. 在遍历中的每个节点处,我们输出 D 条短划线(其中 D 是该节点的深度) 然后输出该节点的值.(如果节点的深度为 D,则其 ...

  7. Docusaurus之markdown文档的vscode代码片段

    需求 我是使用Docusaurus建立的个人站点,在写文档是总是要在开头配置作者.日期等等,用过Docusaurus的都应该知道. 因为每次新建一个md文档都需要重新配置,很麻烦,于是我就想能不能新建 ...

  8. dpkg 安装mysql

    名称 版本 系统 Ubuntu 16.04 MySQL 5.7.26 下载安装包 wget https://dev.mysql.com/get/Downloads/MySQL-8.mysql-serv ...

  9. boot 项目启动:Error starting ApplicationContext. To display the conditions report re-run

    Error starting ApplicationContext. To display the conditions report re-run 问题描述 boot 工程启动不了 原因分析: 以后 ...

  10. 微服务bug之:openFeign远程调用返回类型转换异常

    楼主是在使用easyexcel导出的时候,获取数据出现这个错误,因为Spring底层是这样处理的使用LinkedhashMap来承接查询结果,导致转换异常 public List<NeedAll ...