You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RNFetchBlob.fs.writeFile完成时通知用户(非弹窗方式)

替换RNFetchBlob写入后的alert弹窗为非弹窗式通知

嘿,我来给你分享几个在React Native里替代alert做非弹窗式通知的实用方案,都是项目里常用的,你可以根据自己的需求选:

1. 用React Native内置的ToastAndroid(仅Android)

如果你的应用只需要支持Android,直接用官方自带的ToastAndroid就够了,不用额外装依赖包,简单高效:

import { ToastAndroid } from 'react-native';

RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
  .then(res => {
    console.log(res);
    if (res > 0) {
      // 短时长显示在屏幕底部
      ToastAndroid.showWithGravity('文件写入成功', ToastAndroid.SHORT, ToastAndroid.BOTTOM);
    } else {
      ToastAndroid.showWithGravity('文件写入失败', ToastAndroid.SHORT, ToastAndroid.BOTTOM);
    }
  })
  .catch(err => {
    // 别忘了捕获错误,给用户反馈
    ToastAndroid.show(`写入出错:${err.message}`, ToastAndroid.LONG);
  });

2. 跨平台Toast库(react-native-toast-message)

要是需要同时支持iOS和Android,这个库是个不错的选择,样式还能自定义,体验统一:

首先安装依赖:

npm install react-native-toast-message
# 或者用yarn:yarn add react-native-toast-message

然后在你的根组件(比如App.js)里注册Toast组件:

import Toast from 'react-native-toast-message';

function App() {
  return (
    <>
      {/* 你的其他业务组件 */}
      <Toast />
    </>
  );
}

最后在文件写入的逻辑里调用:

import Toast from 'react-native-toast-message';

RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
  .then(res => {
    console.log(res);
    if (res > 0) {
      Toast.show({
        type: 'success',
        text1: '操作成功',
        text2: '文件已成功写入存储',
        visibilityTime: 2500, // 通知显示时长(毫秒)
        autoHide: true,
      });
    } else {
      Toast.show({
        type: 'error',
        text1: '操作失败',
        text2: '文件写入未成功,请重试',
      });
    }
  })
  .catch(err => {
    Toast.show({
      type: 'error',
      text1: '出错啦',
      text2: `写入过程发生错误:${err.message}`,
    });
  });

3. 本地状态栏通知(适合后台操作)

如果文件写入是在后台执行的,或者需要更醒目的通知但不想打扰用户操作,可以用本地推送通知的方式,推荐用react-native-push-notification库:

安装配置完成后,先在App启动时初始化:

import PushNotification from 'react-native-push-notification';

PushNotification.configure({
  onNotification: function(notification) {
    // 处理通知被点击的逻辑
    console.log('用户点击了通知', notification);
  },
});

然后在文件写入完成后触发通知:

RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
  .then(res => {
    console.log(res);
    if (res > 0) {
      PushNotification.localNotification({
        title: '文件操作完成',
        message: '文件已成功写入你的设备',
        vibrate: true,
        vibration: 300,
        playSound: true,
        soundName: 'default',
      });
    } else {
      PushNotification.localNotification({
        title: '文件操作失败',
        message: '文件写入未成功,请检查后重试',
      });
    }
  })
  .catch(err => {
    PushNotification.localNotification({
      title: '写入错误',
      message: `文件写入过程出错:${err.message}`,
    });
  });

小提醒

不管用哪种方案,都记得加上catch块捕获异步操作的错误,避免出现操作失败但用户完全不知情的情况哦~

内容的提问来源于stack exchange,提问作者Abhishek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:59:06