React Native實現Toast輕提示和loading

来源:https://www.cnblogs.com/LannyChung/archive/2023/08/31/17670013.html
-Advertisement-
Play Games

# React Native 封裝Toast ## 前言 > 使用react native的小伙伴都知道,官方並未提供輕提示組件,只提供了ToastAndroid API,顧名思義,只能再安卓環境下使用,對於ios就愛莫能助,故此,只能通過官方的核心組件,自行封裝,實現Toast功能 ## 實現 * ...


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(); // 手動關閉

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 我喜歡Kusto (或商用版本 Azure Data Explorer,簡稱 ADX) 是大家可以有目共睹的,之前還專門寫過這方面的書籍,請參考 [大數據分析新玩法之Kusto寶典](https://kusto.book.xizhang.com), 很可能在今年還會推出第二季,正在醞釀題材和場景中。 ...
  • 一、事務簡介 事務是一組操作的集合,它是一個不可分割的工作單位,事務會把所有操作作為一個整體一起向系統提交或者撤銷操作請求,即這些操作要麼同時成功,要麼同時失敗。mysql的事務預設是自動提交的,也就是說,當執行一條DML語句,Mysql會立即隱式的提交事務 二、事務操作 2.1 查看事務提交方式 ...
  • 8月16-18日,第14屆中國資料庫技術大會 (DTCC2023) 在北京召開。在18日的DTCC2023“大數據平臺架構與應用案例(上)”專場,天翼雲科技有限公司資料庫產品線總監葉小朋分享了天翼雲資料庫在多雲場景下的探索,以及一站式資料庫多雲管理平臺TeleDB-DCP的產品能力和落地實踐。 ...
  • 8月30日,由 NineData 和 SelectDB 共同舉辦的主題為“實時數據驅動,引領企業智能化數據管理”的線上聯合發佈會,圓滿成功舉辦!雙方聚焦於實時數據倉庫技術和數據開發能力,展示如何通過強大的生態開發相容性,對接豐富的大數據生態產品,助力企業快速開展數據分析業務,共同探索實時數據驅動的未... ...
  • ![file](https://img2023.cnblogs.com/other/3195851/202308/3195851-20230831114702799-1091292653.jpg) 提到數據處理,經常有人把它簡稱為“ETL”。但仔細說來,數據處理經歷了ETL、ELT、XX ETL(例 ...
  • ![file](https://img2023.cnblogs.com/other/2685289/202308/2685289-20230831101757216-1368442529.png) 作者 | 李晨 編輯 | Debra Chen 數據準備對於推動有效的自助式分析和數據科學實踐至關重要 ...
  • 一、尋找合適的線上預覽Excel的js庫 我: 線上預覽Excel文件有哪些好用的js庫 ChatGPT: 有幾個好用的JavaScript庫可以用來在網頁上實現線上預覽Excel文件。以下是一些常見且功能強大的庫: SheetJS (xlsx.js): 這是一個功能強大的庫,可以在網頁上實現Exc ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 問題描述:最近工作中出現一個需求,純前端下載 Excel 數據,並且有的下載內容很多,這時需要給下載增加一個 loading 效果。 代碼如下: // utils.js const XLSX = require('xlsx') // 將一 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...