React Native实现Toast轻提示和loading

这篇具有很好参考价值的文章主要介绍了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调用

挂载完成,接下来,在我们需要用到的地方,调用即可文章来源地址https://www.toymoban.com/news/detail-684995.html

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的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • uniapp中uview组件库Toast 消息提示 的使用方法

    目录 #基本使用 #配置toast主题 #toast结束跳转URL #API #Props #Params #Methods 此组件表现形式类似uni的 uni.showToast API,但也有不同的地方,具体表现在: uView的 toast 有5种主题可选 可以配置toast结束后,跳转相应URL 目前没有加载中的状态,请用uni的 uni.showLoading ,这个需求uni已经做得

    2024年01月20日
    浏览(29)
  • 【Vant4】Vant4 样式不显示问题 && Toast 轻提示不显示 && Notify 消息提示不显示

    使用 Toast 轻提示 和 Notify 消息提示 时没有样式,如下图 引入所需的样式,例如: 我要使用 消息提示 (Notify),就引入 import \\\'vant/es/notify/style\\\' 我要使用 轻提示 (Toast),就引入 import \\\'vant/es/toast/style\\\' HomeView.vue End 2023/3/7 一改 【Vue3】vue3的keepAlive保存滚动位置 CKEditor5 添加代码高亮

    2023年04月18日
    浏览(25)
  • vue自定义全局弹出询问框、输入框、提示框、toast(附源码)

    早前写过一篇关于vue自定义弹出询问框、输入框、提示框的贴子,当时只是实现了组件化,组件需要在各个业务模板进行引用,不能全局化使用,不太方便,本次将其改进成了全局使用,具体的业务模块不需要引入组件,直接调用main.js注册的全局方法即可。 涉及技术点: 遮

    2024年02月03日
    浏览(15)
  • 【微信小程序创作之路】- 小程序事件绑定、动态提示Toast、对话框 Modal

    第六章 小程序事件绑定、动态提示Toast、对话框 Modal 本章主要讲解小程序事件绑定、动态提示Toast、对话框 Modal,结合代码示例,我们来研究一下! 事件是 视图层到逻辑层的通讯方式 。事件是小程序和用户互动的主要方式,通过事件将用户在 视图层 的行为,反馈到 逻辑层

    2024年02月14日
    浏览(27)
  • react native 0.73 配置 react-native-fs

    npm yarn android/settings.gradle android/app/build.gradle androidappsrcmainjavacomreactnative_demoMainApplication.kt 把原代码 改为

    2024年04月08日
    浏览(25)
  • 探索React Native的世界:gorhom/react-native-animated-tabbar

    项目地址:https://gitcode.com/gorhom/react-native-animated-tabbar 在移动应用开发领域,React Native以其高效、跨平台的能力受到了广泛的欢迎。今天,我们要向您推荐一个极具创意且实用的React Native组件库——gorhom/react-native-animated-tabbar。它是一个精美设计的动画TabBar,为您的应用提供生

    2024年04月17日
    浏览(42)
  • React与React Native的异同

    开发React一段时间了,一直没有搞清楚React和React Native的差异。今天特意去了解下,发现差异还真不小! 相同点: 1.都是Facebook公司推出的框架。 2.都是基于JSX语言开发的。 差异点: 1、作用的平台不同. 2、工作原理不同. 3、渲染周期不同. 4、组件构成形式不同. 5、宿主平台的

    2024年02月06日
    浏览(22)
  • 维护积极的react native,为什么会有人造谣react native不维护了,停止维护。

            其实近几年我一直关注react -native,他一直更新频繁,0.60大重构,升级了js执行引擎Hermes,当前已经0.70.4版本了。性能越来越提高,但是总感觉到有人在刷百度,只要输入react-native后面就自动提示热搜“react-native 停止维护”,这误导很多人以为真的不维

    2024年02月11日
    浏览(23)
  • 工欲善其事,必先利其器之—react-native-debugger调试react native应用

    调试react应用通常利用chrome的inspector的功能和两个最常用的扩展 1、React Developer Tools (主要用于debug组件结构) 2、Redux DevTools (主要用于debug redux store的数据) 对于react native应用,我们一般就使用react-native-debugger了,它是一个独立的应用,需要单独安装,在mac下可以用如下命令

    2024年02月16日
    浏览(18)
  • React Native 环境安装

    Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.   搭建开发环境 · React Native 中文网 Homebrew(包管理器) → rvm(ruby版本管理) → ruby → cocoapods 安装 Homebrew Homebrew 安装RVM 使用RVM 安装Ruby RVM 查看版本,并设置默认Ruby版本 安装cocoapods pod 生成项目 进入指定目录下

    2024年01月22日
    浏览(25)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包