React Native实现Toast轻提示和loading
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的更多相关文章
- React Native封装Toast与加载Loading组件
React Native开发封装Toast与加载Loading组件 在App开发中,我们避免不了使用的两个组件,一个Toast,一个网络加载Loading,在RN开发中,也是一样,React Nati ...
- React Native之通知栏消息提示(android)
React Native之通知栏消息提示(android) 一,需求分析与概述 1.1,推送作为手机应用的基本功能,是手机应用的重要部分,如果自己实现一套推送系统费时费力,所以大部分的应用都会选择使用 ...
- React Native之通知栏消息提示(ios)
React Native之通知栏消息提示(ios) 一,需求分析与概述 详情请查看:React Native之通知栏消息提示(android) 二,极光推送注册与集成 2.1,注册 详情请查看:Rea ...
- WebStorm开发工具设置React Native智能提示
最近在做React Native开发的时候,相信大家一般会使用WebStorm,Sublime,Atom等等开发工具.二之前搞前端的对WebStorm会很熟悉,WebStorm最新版是WebStorm ...
- React native 开发工具 VSCode
1.VSCODE下载地址:先下载VSCode软件 2.代码提示功能: 打开 VSCode ,然后 按住键盘 command+p,然后在vscode上面输入框 输入: "ext install ...
- 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 ...
- [react native] Error loading page
如上图显示的错误,解决方法如下: 在react native ios项目的info.plist文件中,新增一个属性. 在Info.plist中添加NSAppTransportSecurity类型Dic ...
- React Native:使用 JavaScript 构建原生应用
[转载] 本篇为联合翻译,译者:寸志,范洪春,kmokidd,姜天意 数月前,Facebook 对外宣布了正在开发的 React Native 框架,这个框架允许你使用 JavaScript 开发原生 ...
- react native 入门实践
上周末开始接触react native,版本为0.37,边学边看写了个demo,语法使用es6/7和jsx.准备分享一下这个过程.之前没有native开发和react的使用经验,不对之处烦请指出.希望 ...
- iOS原生项目中集成React Native
1.本文的前提条件是,电脑上已经安装了CocoaPods,React Native相关环境. 2.使用Xcode新建一个工程.EmbedRNMeituan [图1] 3.使用CocoaPods安装Re ...
随机推荐
- 「P2」试下1个半月能不能水出个毕设
0.目标 将上个 springboot 项目 + html 中的html用Vue来重写,也就是在原springboot项目中集成Vue 1.在界面上,将html改成vue的形式 1.1.原html & ...
- Qt数据可视化项目
一.创建项目(步骤按常规来即可) 二.ui设计界面 控件的使用 默认视角:Label标签和horizontalSlider标签 水平旋转:Label标签和horizontalSlider标签 垂直旋转 ...
- SpringBoot 使用 Sa-Token 完成路由拦截鉴权
一.需求分析 在前文,我们详细的讲述了在 Sa-Token 如何使用注解进行权限认证,注解鉴权虽然方便,却并不适合所有鉴权场景. 假设有如下需求:项目中所有接口均需要登录认证校验,只有 "登 ...
- Python基础 - 算数运算符
算数运算符 运算符 描述 实例 + 加 - 两个对象相加 a + b 输出结果 30 - 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -10 * 乘 - 两个数相乘或是返回一个被 ...
- odoo开发教程五:高级视图
树视图 tree视图表现出来是列表视图,列表中一行一纪录.可以根据每行纪录的某字段值不同而把每行以不同样式显示. decoration-{样式}="条件" 样式主要有: bf(fo ...
- CSS3 clip-path:打造独特创意设计效果的秘密武器
大家好,我是程序视点的小二哥. 今天小二哥将给大家分享一篇有前端实验室的文章.一部由CSS技术实现的作品.它将再一次证明CSS的强大力量. 欣赏 这是一部由阿姆斯特丹设计师Bryan James通过3 ...
- 7-9 《Fibonacci 数列》
7-9 <Fibonacci 数列> 思路:吃过前面<序列求和>问题的亏 但还是要尝试一下循环大法 Fn=Fn-1+Fn-2 定义int型 aFn-1 , bFn-2 , cF ...
- SQL Server 2008/2012 完整数据库备份+差异备份+事务日志备份 数据库完整还原(一)
还原方案 数据库级(数据库完整还原) 还原和恢复整个数据库.数据库在还原和恢复操作期间会处于离线状态.SQL SERVER不允许用户备份或还原单个表.还原方案是指从一个或多个备份中还原数据.继而恢复数 ...
- 有懂的没,json对象中 嵌入 json字符串 它规范吗?
json字符串 和 json对象 1.JSONObject中的String json串中data对应的值是String,String字符串中双引号需要使用反斜杠\进行转义, 痛恨这种, 解析时要进行二 ...
- 【Unity3D】魔方
1 需求实现 绘制魔方 中基于OpenGL ES 实现了魔方的绘制,实现较复杂,本文基于 Unity3D 实现了 2 ~ 10 阶魔方的整体旋转和局部旋转. 本文完整代码资源见→基于 Unit ...