这几天整理了一下分享功能,目前整理了QQ,微信,系统的分享功能。分享类型有文本,链接,图片。其实还有微博没有对接,目前我还没找到好用一点的微博的 RN 组件库(有机会的话自己写一个吧)然后还有视频分享类型没有去折腾(不过现在分享视频的场景也比较少吧,之后再整吧)

首先看看需要用到的库:

rn-fetch-blob(文件下载库):https://github.com/joltup/rn-fetch-blob

react-native-share(系统分享库):https://github.com/react-native-community/react-native-share

react-native-wechat-lib(微信分享登陆支付 SDK 封装):https://github.com/little-snow-fox/react-native-wechat-lib

react-native-qq-lib(QQ 登陆分享 SDK 封装):https://github.com/haxibiao/react-native-qq-lib

安装使用 rn-fetch-blob

可以通过 npm 或者 yarn 直接安装

npm install --save rn-fetch-blob

# 或者

yarn add rn-fetch-blob

安装成功后开始配置 Android 权限,打开 AndroidManifest.xml 文件,具体路径在你项目的 android/app/src/main 目录下

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rnfetchblobtest"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

    <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
    </intent-filter>

...

配置好之后就可以使用了,安装这个模块的作用主要是 QQ 分享网络图片需要先下载图片,我们为了封装一个通用的分享工具类肯定是要做处理的。

下面代码是一个简单使用的示例

import RNFetchBlob from 'rn-fetch-blob';

const url = "https://bin.zmide.com/zmidelogo.png";

RNFetchBlob.config({
   fileCache: true,
   appendExt: 'png',
})
.fetch('GET', url)
.then(res => {
   console.log("图片下载成功", res);
})
.catch(error => {
    console.log("图片下载失败", error);
});

安装使用 react-native-share

react-native-share 是一个非常强大的分享组件,已被收录到 react-native-community 中了。使用和兼容性也是非常的高,而且好像对国外的部分社交软件分享功能的封装也有很强的支持,使用起来也非常简单,我这里就只是针对唤起系统分享功能分享文本,网页,图片做一个简单的使用示例,更多高级用法可以看看官方文档https://react-native-community.github.io/react-native-share/

首先是安装模块,我们可以通过 npm 或者 yarn 来安装

npm install --save react-native-share

# 或者

yarn add react-native-share

安装之后直接就可以使用了,接下来我将演示如何分享文本,网页,图片功能

import SystemShare from 'react-native-share';

// 分享文本
const text = "这是一段示例文本,Hello World!!!";
SystemShare.open({
    title: '分享给朋友',
    message: text,
}).then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享网页链接
const webUrl = "https://bin.zmide.com/?p=666";
SystemShare.open({
    title: '分享给朋友',
    url: webUrl,
}).then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});

// 分享图片(支持网络地址和本地文件路径)
const image = "https://bin.zmide.com/zmidelogo.png"
SystemShare.open({ url: image })
.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});

安装使用 react-native-wechat-lib

首先是安装模块,我们可以通过 npm 或者 yarn 来安装

npm install --save react-native-wechat-lib

# 或者

yarn add react-native-wechat-lib

react-native-wechat-lib 安装之后的配置就会稍微有点复杂了,不过没关系只要我们一步步来还是很容易搞定的。

前期需要先申请微信的 app id 了,打开微信开发者平台(https://open.weixin.qq.com/)申请就可以了。这里我就不详情介绍申请的过程了,需要帮助的小伙伴可以评论留言。

首先配置 Android,在你的项目的 android/app/src/main/java/com/demo/ 文件夹下面创建一个 wxapi 文件夹(这里的文件路径中的 com/demo 是你自己的 app 包名不要照抄,包括下面代码出现的 com.demo 或者 com/demo 路径时记得用自己包名代替不知道自己包名的可以看看 app.json 中的 AppID 字段 )。

然后在 wxapi 文件夹中创建 WXEntryActivity.java 文件,写入下列代码(记得把 com.demo 替换成自己包名)

package com.demo.wxapi;

import android.app.Activity;
import android.os.Bundle;
import com.theweflex.react.WeChatModule;

public class WXEntryActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WeChatModule.handleIntent(getIntent());
    finish();
  }
}

接下来找到 AndroidManifest.xml 文件,添加这个 Activity

……

<manifest>
  <application>
    <activity
      android:name=".wxapi.WXEntryActivity"
      android:label="@string/app_name"
      android:exported="true"
    />
  </application>
</manifest>

……

然后打开 MainApplication.java 文件添加我们的微信包,如下代码

import com.theweflex.react.WeChatPackage; // 添加这一行

  @Override
  protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    // Packages that cannot be autolinked yet can be added manually here, for example:
    // packages.add(new MyReactNativePackage());
    packages.add(new WeChatPackage()); // 大概在这个位置添加这一行
    return packages;
  }

如果遇到安卓 App 拉起小程序后,小程序无法返回 App 的情况,需要在 AndroidManifest.xml 的 WXEntryActivity 中添加下面这段配置(记得把 com.demo 替换成自己包名):

android:taskAffinity="com.demo"
android:launchMode="singleTask"

保证跳转后回到你的 app 的 task 。
实际上,我的代码如下(记得把 com.demo 替换成自己包名):

<manifest>
  <application>
    <activity
      android:name=".wxapi.WXEntryActivity"
      android:label="@string/app_name"
      android:exported="true"
      android:taskAffinity="com.demo.rnapp"
      android:launchMode="singleTask"
    />
  </application>
</manifest>

到这里我们 Android 的配置基本完成了,接下来就是 IOS 中的配置了。

xcode 打开 app "URL type" 找到 Targets > info ,添加 URL Schema,如下图所示(URL Schemes 的输入框填你自己申请到的 appid 记得加 wx 前缀)

这可能是 React Native 对接国内社交软件分享功能最全最详细的博客了-天真的小窝

编辑 Info.plist 文件,添加下面的 xml 代码(如果不配置,因为安全权限问题,苹果会阻止你跳转到微信。)

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>weixin</string>
  <string>wechat</string>
  <string>weixinULAPI</string>
</array>

编辑 AppDelegate.m 文件,添加回调方法(如果不配置,分享的时候微信会出现"正在连接",然后直接弹回APP。)

#import <React/RCTLinkingManager.h>

………

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application
  continueUserActivity:(NSUserActivity *)userActivity
  restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable
  restorableObjects))restorationHandler {
  // 触发回调方法
  [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
  return [WXApi handleOpenUniversalLink:userActivity
  delegate:self];
}

编辑 AppDelegate.h 文件(主要是需要加上 '#import "WXApi.h"' 和 'WXApiDelegate' 。)

#import <React/RCTBridgeDelegate.h>
#import <UIKit/UIKit.h>
#import "WXApi.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, WXApiDelegate>

@property (nonatomic, strong) UIWindow *window;

@end

好了现在原生代码配置都完成了,接下来看看怎么使用

首先我们需要在 app 的 useEffect 生命周期中初始化 SDK,需要用到 wxappid 和universalLink 可以在微信开发者平台设置和找到(这个只需要在 app 启动的时候初始化一次就好了)

useEffect(() => {
    const wxappid = 'wx11111999999';
    const universalLink = 'http://demo.com'; // 注意区分 https 和 http 必须和你在微信开发者后台填的保持一致

    WeChat.registerApp(wxappid, universalLink)
        .then(registerApp => {
            console.log('registerApp', registerApp);
        })
        .catch(error => {
            console.log('error', error);
        });

}, []);

初始化之后我们看看怎么调用各种分享方法(其他像微信登陆,微信支付啥的不是本篇博客的内容,我就不多 BB 了,需要的小伙伴可以参考参考官方文档)

import * as WeChat from 'react-native-wechat-lib';

// 分享文本到微信好友
const text = "这是一段分享文本,Hello world!";
const weichat = WeChat.shareText({ text, scene: 0, });
weichat.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享文本到微信朋友圈
const text = "这是一段分享文本,Hello world!";
const weichat = WeChat.shareText({ text, scene: 1, });
weichat.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享网页给微信好友
const weichat = WeChat.shareWebpage({
    title: '这是网页标题!',
    description: '这是一段网页的描述呀!',
    webpageUrl: 'https://bin.zmide.com/',
    thumbImageUrl: 'https://bin.zmide.com/zmlogo.png',
    scene: 0,
});
weichat.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享网页给微信朋友圈
const weichat = WeChat.shareWebpage({
    title: '这是网页标题!',
    description: '这是一段网页的描述呀!',
    webpageUrl: 'https://bin.zmide.com/',
    thumbImageUrl: 'https://bin.zmide.com/zmlogo.png',
    scene: 1,
});
weichat.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享图片给微信好友
const weichat = WeChat.shareLocalImage({
    imageUrl: 'https://bin.zmide.com/',
    scene: 0,
})
weichat.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享图片给微信朋友圈
const weichat = WeChat.shareLocalImage({
    imageUrl: 'https://bin.zmide.com/',
    scene: 1,
})
weichat.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});

安装 react-native-qq-lib

申请 QQ sdk 的 appid 的话可以去 QQ 互联平台(https://connect.qq.com/

然后是安装模块,我们可以通过 npm 或者 yarn 来安装

npm install --save github:haxibiao/react-native-qq-lib

# 或者

yarn add github:haxibiao/react-native-qq-lib

现在开始配置 Android,在 android/app/build.gradle 里,defaultConfig 栏目下添加如下代码:

manifestPlaceholders = [
    QQ_APPID: "<平台申请的APPID>"
]

另外,确保你的 MainActivity.java 中有 onActivityResult 的实现:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    mReactInstanceManager.onActivityResult(requestCode, resultCode, data);
}

这样我们 Android 部分就配置好了,现在我们配置一下 ios ,首先执行 pod 安装依赖

cd ios && pod install && cd ..

在工程 plist 文件中加入 qq 白名单:(ios9 以上必须) 请以文本方式打开 Info.plist ,在其中添加(如果配置了微信的记得放一起)

<key>LSApplicationQueriesSchemes</key>
<array>
    <!-- QQ、Qzone URL Scheme 白名单-->
    <string>mqqapi</string>
    <string>mqq</string>
    <string>mqqOpensdkSSoLogin</string>
    <string>mqqconnect</string>
    <string>mqqopensdkdataline</string>
    <string>mqqopensdkgrouptribeshare</string>
    <string>mqqopensdkfriend</string>
    <string>mqqopensdkapi</string>
    <string>mqqopensdkapiV2</string>
    <string>mqqopensdkapiV3</string>
    <string>mqzoneopensdk</string>
    <string>wtloginmqq</string>
    <string>wtloginmqq2</string>
    <string>mqqwpa</string>
    <string>mqzone</string>
    <string>mqzonev2</string>
    <string>mqzoneshare</string>
    <string>wtloginqzone</string>
    <string>mqzonewx</string>
    <string>mqzoneopensdkapiV2</string>
    <string>mqzoneopensdkapi19</string>
    <string>mqzoneopensdkapi</string>
    <string>mqzoneopensdk</string>
 </array>

Info -> URL Types 中增加 QQ 的 scheme: Identifier 设置为qqURL Schemes 设置为你注册的 QQ 开发者账号中的 APPID,需要加前缀tencent,例如 tencent1104903684

这可能是 React Native 对接国内社交软件分享功能最全最详细的博客了-天真的小窝

在你工程的 AppDelegate.m 文件中添加如下代码:

#import <React/RCTLinkingManager.h>

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
  return [RCTLinkingManager application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}

好了现在我们 react-native-qq-lib 就配置完成了,我们看看怎么使用各种分享功能吧

import * as QQAPI from 'react-native-qq-lib';
import RNFetchBlob from 'rn-fetch-blob';


// 分享文本到 QQ 好友
const text = "这是一段分享文本,Hello world!";
const qq = QQAPI.shareToQQ({
    type: 'text',
    text,
});
qq.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享文本到 QQ 空间
const text = "这是一段分享文本,Hello world!";
const qq = QQAPI.shareToQzone({
    type: 'text',
    text,
});
qq.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享网页给QQ好友
const qq = QQAPI.shareToQQ({
    type: 'news',
    title: "这是一个网页的标题!",
    description: "一段网页的描述!",
    webpageUrl: "https://bin.zmide.com",
    imageUrl: "https://bin.zmide.com/zmlogo.png",
});
qq.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享网页给QQ空间
const qq = QQAPI.shareToQzone({
    type: 'news',
    title: "这是一个网页的标题!",
    description: "一段网页的描述!",
    webpageUrl: "https://bin.zmide.com",
    imageUrl: "https://bin.zmide.com/zmlogo.png",
});
qq.then((res: any) => {
    console.log("分享成功", res);
}).catch((err: any) => {
    console.log("分享失败", err);
});


// 分享图片到QQ好友
const image = 'https://bin.zmide.com/zmlog.png';
if (RegExp(/http:\/\//).exec(image) || RegExp(/https:\/\//).exec(image)) {
    // 判断是网络地址的话先下载图片,然后再分享图片

    RNFetchBlob.config({
        fileCache: true,
        appendExt: 'png',
    })
        .fetch('GET', image)
        .then(res => {

            const qq = QQAPI.shareToQQ({
                type: 'image',
                imageUrl: res.path(),
                imageLocalUrl: res.path(),
            });
            qq.then((res: any) => {
                console.log("分享成功", res);
            }).catch((err: any) => {
                console.log("分享失败", err);
            });

        })
        .catch(error => {
            console.log("分享失败", error);
        });

} else {
    const qq = QQAPI.shareToQQ({
        type: 'image',
        imageUrl: image,
        imageLocalUrl: image,
    });
    qq.then((res: any) => {
        console.log("分享成功", res);
    }).catch((err: any) => {
        console.log("分享失败", err);
    });
}


// 分享图片到QQ空间
const image = 'https://bin.zmide.com/zmlog.png';
if (RegExp(/http:\/\//).exec(image) || RegExp(/https:\/\//).exec(image)) {
    // 判断是网络地址的话先用 RNFetchBlob 下载图片,然后再分享图片

    RNFetchBlob.config({
        fileCache: true,
        appendExt: 'png',
    })
        .fetch('GET', image)
        .then(res => {

            const qq = QQAPI.shareToQzone({
                type: 'image',
                imageUrl: res.path(),
                imageLocalUrl: res.path(),
            });
            qq.then((res: any) => {
                console.log("分享成功", res);
            }).catch((err: any) => {
                console.log("分享失败", err);
            });

        })
        .catch(error => {
            console.log("分享失败", error);
        });

} else {
    const qq = QQAPI.shareToQzone({
        type: 'image',
        imageUrl: image,
        imageLocalUrl: image,
    });
    qq.then((res: any) => {
        console.log("分享成功", res);
    }).catch((err: any) => {
        console.log("分享失败", err);
    });
}

到这里我们基本对接好了国内主流社交聊天软件 QQ 和微信的分享,最后我再分享一个我已经整理好的分享工具方法吧

import RNFetchBlob from 'rn-fetch-blob';
import SystemShare from 'react-native-share';
import * as WeChat from 'react-native-wechat-lib';
import * as QQAPI from 'react-native-qq';

export type webSiteProps = {
    url: string,
    title?: string,
    description?: string,
    thumbImage?: string
}

export type imageProps = {
    imageUrl?: string,
    imagePath?: string,
}

export interface toShareProps {
    platform: '微信' | '朋友圈' | 'QQ' | 'QQ空间' | '微博' | '其他';
    type?: 'text' | 'website' | 'image';
    text?: string;
    webSite?: webSiteProps;
    image?: imageProps;
    onSucceed?: () => void;
    onError?: (err?: any) => void;
}

const toShare = (share: toShareProps) => {
    const { platform = '其他', onSucceed = () => { }, onError = (err: any) => { } } = share;
    let { type } = share;

    // 实现错误回调方法
    const __onError = (code: number, msg: string) => {
        onError({ code, msg });
    };

    // 实现成功回调方法
    const __onSucceed = () => {
        onSucceed();
    };

    // 判断是否存在分享内容
    if (!share.text && !share.image && !share.webSite) {
        __onError(-1, '不存在分享内容!');
        return;
    }

    // 当分享类型没有指定,执行智能判断分享类型兼容
    if (!type) {
        if (share.text) {
            type = 'text';
        } else if (share.image) {
            type = 'image';
        } else if (share.webSite) {
            type = 'website';
        }
    }

    const __text_wx = (text: string) => {
        // 开始实现微信 text 分享
        const weichat = WeChat.shareText({
            text,
            scene: 0,
        });

        weichat.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享文本到微信好友失败!');
        });
    };
    const __text_pyq = (text: string) => {
        // 开始是实现朋友圈 text 分享
        const weichat = WeChat.shareText({
            text,
            scene: 1,
        });

        weichat.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享文本到朋友圈失败!');
        });

    };
    const __text_qq = (text: string) => {
        const qq = QQAPI.shareToQQ({
            type: 'text',
            text,
        });
        qq.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享文本到QQ好友失败!');
        });
    };
    const __text_qqz = (text: string) => {
        // TODO: Android QQ 客户端不行
        // Android 的 QQ空间客户端应该可以
        const qq = QQAPI.shareToQzone({
            type: 'text',
            text,
        });
        qq.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享文本到QQ空间失败!');
        });
    };
    const __text_wb = (text: string) => {
    };
    const __text_sys = (text: string) => {
        SystemShare.open({
            title: '分享给朋友',
            message: text,
        }).then((res: any) => {
            __onSucceed();
        }).catch((err: any) => {
            __onError(0, '调用系统分享文本失败');
        });
    };

    const __website_wx = (webSite: webSiteProps) => {
        const weichat = WeChat.shareWebpage({
            title: webSite.title || '',
            description:
                webSite.description || '',
            webpageUrl: webSite.url,
            thumbImageUrl: webSite.thumbImage,
            scene: 0,
        });
        weichat.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享网页到微信好友失败!');
        });
    };
    const __website_pyq = (webSite: webSiteProps) => {
        const weichat = WeChat.shareWebpage({
            title: webSite.title || '',
            description:
                webSite.description || '',
            webpageUrl: webSite.url,
            thumbImageUrl: webSite.thumbImage,
            scene: 1,
        });
        weichat.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享网页到朋友圈失败!');
        });
    };
    const __website_qq = (webSite: webSiteProps) => {
        // TODO: Android 出现未知应用不可分享
        const qq = QQAPI.shareToQQ({
            type: 'news',
            title: webSite.title,
            description: webSite.description,
            webpageUrl: webSite.url,
            imageUrl: webSite.thumbImage,
        });
        qq.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享网页到QQ好友失败!');
        });
    };
    const __website_qqz = (webSite: webSiteProps) => {
        const qq = QQAPI.shareToQzone({
            type: 'news',
            title: webSite.title,
            description: webSite.description,
            webpageUrl: webSite.url,
            imageUrl: webSite.thumbImage,
        });
        qq.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享网页到QQ空间失败!');
        });
    };
    const __website_wb = (webSite: webSiteProps) => { };
    const __website_sys = (webSite: webSiteProps) => {
        SystemShare.open({
            title: '分享给朋友',
            url: webSite.url,
        }).then((res: any) => {
            __onSucceed();
        }).catch((err: any) => {
            __onError(0, '调用系统分享网页失败');
        });;
    };

    const __image_wx = (image: imageProps) => {
        const { imageUrl, imagePath } = image;
        if (!imageUrl && !imagePath) {
            __onError(-1, '分享图片给微信失败!图片 Url 或者 Path,必传一个');
            return;
        }

        let weichat;
        if (imageUrl) {
            weichat = WeChat.shareImage({
                imageUrl,
                scene: 0,
            });
        } else if (imagePath) {
            weichat = WeChat.shareLocalImage({
                imageUrl: imagePath,
                scene: 0,
            })
        } else {
            __onError(1, '分享图片到微信好友失败!');
            return;
        }
        
        weichat.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享图片到微信好友失败!');
        });

    };
    const __image_pyq = (image: imageProps) => {
        const { imageUrl, imagePath } = image;
        if (!imageUrl && !imagePath) {
            __onError(-1, '分享图片给朋友圈失败!图片 Url 或者 Path,必传一个');
            return;
        }

        let weichat;
        if (imageUrl) {
            weichat = WeChat.shareImage({
                imageUrl,
                scene: 0,
            });
        } else if (imagePath) {
            weichat = WeChat.shareLocalImage({
                imageUrl: imagePath,
                scene: 0,
            })
        } else {
            __onError(1, '分享图片到朋友圈失败!');
            return;
        }

        weichat.then(() => {
            __onSucceed();
        }).catch(() => {
            __onError(0, '分享图片到朋友圈失败!');
        });
    };
    const __image_qq = (image: imageProps) => {

        const { imageUrl, imagePath } = image;
        if (!imageUrl && !imagePath) {
            __onError(-1, '分享图片给QQ失败!图片 Url 或者 Path,必传一个');
            return;
        }
        const _image = imageUrl || imagePath || '';

        if (RegExp(/http:\/\//).exec(_image) || RegExp(/https:\/\//).exec(_image)) {
            // 判断是网络地址的话先下载图片,然后再分享图片

            RNFetchBlob.config({
                fileCache: true,
                appendExt: 'png',
            })
                .fetch('GET', _image)
                .then(res => {

                    const qq = QQAPI.shareToQQ({
                        type: 'image',
                        imageUrl: res.path(),
                        imageLocalUrl: res.path(),
                    });
                    qq.then(() => {
                        __onSucceed();
                    }).catch(() => {
                        __onError(0, '分享图片到QQ好友失败!');
                    });

                })
                .catch(error => {
                    __onError(0, '分享图片到QQ好友失败!');
                });

        } else {
            const qq = QQAPI.shareToQQ({
                type: 'image',
                imageUrl: _image,
                imageLocalUrl: _image,
            });
            qq.then(() => {
                __onSucceed();
            }).catch(() => {
                __onError(0, '分享图片到QQ好友失败!');
            });
        }


    };
    const __image_qqz = (image: imageProps) => {
        const { imageUrl, imagePath } = image;
        if (!imageUrl && !imagePath) {
            __onError(-1, '分享图片给QQ失败!图片 Url 或者 Path,必传一个');
            return;
        }
        const _image = imageUrl || imagePath || '';

        if (RegExp(/http:\/\//).exec(_image) || RegExp(/https:\/\//).exec(_image)) {
            // 判断是网络地址的话先下载图片,然后再分享图片

            RNFetchBlob.config({
                fileCache: true,
                appendExt: 'png',
            })
                .fetch('GET', _image)
                .then(res => {

                    const qq = QQAPI.shareToQzone({
                        type: 'image',
                        imageUrl: res.path(),
                        imageLocalUrl: res.path(),
                    });
                    qq.then(() => {
                        __onSucceed();
                    }).catch(() => {
                        __onError(0, '分享图片到QQ空间失败!');
                    });

                })
                .catch(error => {
                    __onError(0, '分享图片到QQ空间失败!');
                });

        } else {
            const qq = QQAPI.shareToQzone({
                type: 'image',
                imageUrl: _image,
                imageLocalUrl: _image,
            });
            qq.then(() => {
                __onSucceed();
            }).catch(() => {
                __onError(0, '分享图片到QQ空间失败!');
            });
        }

    };
    const __image_wb = (image: imageProps) => { };
    const __image_sys = (image: imageProps) => {
        const { imageUrl, imagePath } = image;

        if (!imageUrl && !imagePath) {
            __onError(-1, '分享图片给QQ失败!图片 Url 或者 Path,必传一个');
            return;
        }
        const _image = imageUrl || imagePath || '';

        SystemShare.open({ url: _image });
    };

    switch (type) {
        case 'text':
            const text = share.text || '';
            switch (platform) {
                case '微信':
                    __text_wx(text);
                    break;
                case '朋友圈':
                    __text_pyq(text);
                    break;
                case 'QQ':
                    __text_qq(text);
                    break;
                case 'QQ空间':
                    __text_qqz(text);
                    break;
                case '微博':
                    __text_wb(text);
                    break;
                default:
                    __text_sys(text);
                    break;
            }
            break;
        case 'website':
            const website = share.webSite || { url: '' };
            switch (platform) {
                case '微信':
                    __website_wx(website);
                    break;
                case '朋友圈':
                    __website_pyq(website);
                    break;
                case 'QQ':
                    __website_qq(website);
                    break;
                case 'QQ空间':
                    __website_qqz(website);
                    break;
                case '微博':
                    __website_wb(website);
                    break;
                default:
                    __website_sys(website);
                    break;
            }
            break;
        case 'image':
            const image = share.image || {};
            switch (platform) {
                case '微信':
                    __image_wx(image);
                    break;
                case '朋友圈':
                    __image_pyq(image);
                    break;
                case 'QQ':
                    __image_qq(image);
                    break;
                case 'QQ空间':
                    __image_qqz(image);
                    break;
                case '微博':
                    __image_wb(image);
                    break;
                default:
                    __image_sys(image);
                    break;
            }
            break;
    }
};

export default toShare;

将全部平台的分享封装好之后使用起来就非常方便了(或许你注意到了这里我挖了一个微博的坑,以后会出一篇微博的 SDK 封装博客的,这次绝对不鸽…)

这可能是 React Native 对接国内社交软件分享功能最全最详细的博客了-天真的小窝
import toShare from './toShare';

// 分享文本
toShare({
    platform: '微信' | '朋友圈' | 'QQ' | 'QQ空间' | '其他',
    type: 'text',
    text: '这段文本可就厉害了,我跟你港!',
    onSucceed: () => {
        console.log('分享成功');
    },
    onError: (err: any) => {
        console.log('分享错误', err);
    },
});


// 分享网页
toShare({
    platform: '微信' | '朋友圈' | 'QQ' | 'QQ空间' | '其他',
    type: 'website',
    webSite: {
        title: '这是一个神奇的网站',
        description: '一个很有意思网站,分享给你个逗比看看',
        url: 'https://bin.zmide.com',
        thumbImage: 'https://bin.zmide.com/zmlogo.png',
    },
    onSucceed: () => {
        console.log('分享成功');
    },
    onError: (err: any) => {
        console.log('分享错误', err);
    },
});


// 分享网络图片
toShare({
    platform: '微信' | '朋友圈' | 'QQ' | 'QQ空间' | '其他',
    type: 'image',
    image: {
        imageUrl: 'https://bin.zmide.com/zmlogo.png',
    },
    onSucceed: () => {
        console.log('分享成功');
    },
    onError: (err: any) => {
        console.log('分享错误', err);
    },
});


// 分享本地图片
toShare({
    platform: '微信' | '朋友圈' | 'QQ' | 'QQ空间' | '其他',
    type: 'image',
    image: {
        imagePath: '/data/android/com.demo/test.png',
    },
    onSucceed: () => {
        console.log('分享成功');
    },
    onError: (err: any) => {
        console.log('分享错误', err);
    },
});

好了,这篇又臭又长的博客就到这里,有问题的话可以先看看 Github 的项目文档实在不会的可以留下评论我看到就会立即回复的,谢谢大家一直以来的支持和鼓励!