需求说明
点击分享按钮,展示手机内能够打开xlsx文件的APP,将文件分享到其他APP
项目配置
"react-native": "0.59.10",
"react-native-share": "^8.1.0",
"rn-fetch-blob": "0.12.0",
具体配置&操作
(1)获取分享文件下载地址,将文件下载到手机的文件系统中
(2)调用react-native-share
将文件分享到其他应用(APP)
import { Platform } from 'react-native'
const isHaveAndroid = Platform.OS === 'android'
//分享内容
this.shareOptions = {
type: 'file',
title: '一个测试文件.xlsx',
description: '',
}
//获取分享文件下载地址,将文件下载到手机的文件系统中
downloadeExcelFile = async () => {
// downloadFileUrl:文件下载地址
const { downloadFileUrl } = this.props;
let dirs = void 0;
if (isHaveAndroid) {
// 如:RNFetchBlob.fs.dirs.DownloadDir:华为手机可以在手机系统内部存储/download/xlsxDatas找到对应下载的文件
dirs = RNFetchBlob.fs.dirs.DownloadDir + `/xlsxDatas`;
} else {
dirs = RNFetchBlob.fs.dirs.DocumentDir + `/xlsxDatas`;
}
const header = {
'Content-Type': 'application/json',
timestamp: new Date().getTime() + '',
};
const path = `${dirs}/一个测试文件.xlsx`;
// 先检查手机系统中是否存在该文件夹,如果没有则创建该文件夹
const existsRes = await RNFetchBlob.fs.exists(dirs);
if (!existsRes) {
await RNFetchBlob.fs.mkdir(dirs);
}
RNFetchBlob.config({
path,
fileCache: true,
})
.fetch('POST', downloadFileUrl, {
...header,
})
.then((res) => {
this.filePath = res.path();
MessageUtil.hideLoading();
this.handleShareOptions({
// 下载文件成功后,存放在手机文件系统里对应的地址
filePath: this.filePath,
});
return;
})
.catch(() => {
MessageUtil.hideLoading();
MessageUtil.showToast('抱歉,分享失败请稍后重试!');
});
};
// 处理要传递给插件的分享内容
handleShareOptions(params) {
// 由父组件控制分享的内容
const options = {
...this.shareOptions,
...params,
};
const { fileType } = this.props;
let type = '';
// 判断要分享内容的类型
switch (fileType) {
case 'xlsx':
type = 'application/vnd.ms-excel';
break;
default:
}
//调用分享插件进行文件分享
Share.open({
/**
* 加上type这个字段进行分享,安卓会对APP进行过滤,显示可能能够打开的APP,
* ios效果不明显。如果不加上则不能打开xlsx文件的app也会展示出来(如:淘宝)
*/
type,
url: `file://${this.filePath}`,
}).catch((e) => {});
}
展示效果
|
|
|
其他问题
(1)问题描述:当微信未登录时,点击‘用其他应用打开’选中‘微信发送给朋友’时,页面提示‘获取资源失败’
(1.1)此提示框由‘系统分享’弹出,无法通过插件里的代码控制这个提示文案
(1.2)这个‘获取资源失败’问题,暂未找到解决方案
(2)安装react-native-share
插件之后,手机页面无法正常使用,显示报错提示_reactNative.NativeModules.RNShare.FACEBOOK
解决方法:
_reactNative.NativeModules.RNShare.FACEBOOK #322
if React native version < 0.6.0, my React native version === 0.59.10, This parameter can be configured according to version v1.2.1
if Xcode reports an error,can be manually configured
可以使用patch-package
方式修复第三方插件问题
//执行命令
yarn patch-package [react-native-share]
执行成功后,在项目根目录会有patches
文件夹,将文件夹git到远程项目中,后续就不需要手动添加缺少的文件了