@react-native-ohos/react-native-share
v12.1.2
Published
Social share, sending simple data to other apps.
Readme
文档模板:v0.4.1
本项目基于 react-native-share 开发。
该第三方库的仓库已迁移至 Gitcode,且支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-share 版本所属关系如下:
| 三方库名称 | 三方库版本 | 发布信息 | 支持RN版本 | Autolink | 编译API版本 | 社区基线版本 | npm地址 | | ------------ |-------------------------------------------------------------------------------------| ------------------------------ |-----------------|----------|------------------------ |--------| ------------- | | @react-native-ohos/react-native-share | ~ 12.1.2(开发中) | Gitcode Releases | 0.77.* / 0.82.* | partially(0.82) | API12+ | 12.1.0 | Npm Address | | @react-native-ohos/react-native-share | 12.1.1 | Gitcode Releases | 0.77.* | 否 | API12+ | 12.1.0 | Npm Address | | @react-native-ohos/react-native-share | ~ 10.2.2 | Gitcode Releases | 0.72.* | 是 | API12+ | 10.2.1 | Npm Address | | @react-native-oh-tpl/react-native-share | <=10.2.1-0.0.6@deprecated | Github Releases(deprecated) | 0.72.* | 否 | API12+ | 10.2.1 | Npm Address |
简介
react-native-share 是一个简单的工具,用于与其他应用共享消息和文件。
下载安装
进入到工程目录并输入以下命令:
npm
npm install @react-native-ohos/react-native-shareyarn
yarn add @react-native-ohos/react-native-shareLink
| | 是否支持autolink | RN框架版本 | |-----------------------------------|--------------|-----------------| | ~12.1.2 | partially(0.82) | 0.77.* / 0.82.* | | 12.1.1 | 否 | 0.77 |
使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。
首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony。
1. Overrides RN SDK
为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。
关于该字段的作用请阅读官方说明
{
"overrides": {
"@rnoh/react-native-openharmony": "^0.82.1" // ohpm 在线版本
// "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
// "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
}
}2. 引入原生端代码
目前有两种方法:
- 通过 har 包引入;
- 直接链接源码。
方法一:通过 har 包引入(推荐)
[!TIP] har 包位于三方库安装路径的
harmony文件夹下。
打开 entry/oh-package.json5,添加以下依赖
"dependencies": {
"@react-native-ohos/react-native-share": "file:../../node_modules/@react-native-ohos/react-native-share/harmony/react_native_share.har"
}点击右上角的 sync 按钮
或者在命令行终端执行:
cd entry
ohpm install方法二:直接链接源码
[!TIP] 如需使用直接链接源码,请参考直接链接源码说明
3. 配置 CMakeLists 和引入 RNSharePackage
打开 entry/src/main/cpp/CMakeLists.txt,添加:
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-share/src/main/cpp" ./share)
# RNOH_END: manual_package_linking_1
file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")
add_library(rnoh_app SHARED
${GENERATED_CPP_FILES}
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)
# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_share)
# RNOH_END: manual_package_linking_2打开 entry/src/main/cpp/PackageProvider.cpp,添加:
#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "RNSharePackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
std::make_shared<SamplePackage>(ctx),
+ std::make_shared<RNSharePackage>(ctx)
};
}4. 在 ArkTs 侧引入 RNSharePackage
打开 entry/src/main/ets/RNPackagesFactory.ts,添加:
...
+ import {RNSharePackage} from '@react-native-ohos/react-native-share/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
+ new RNSharePackage(ctx)
];
}运行
点击右上角的 sync 按钮
或者在命令行终端执行:
cd entry
ohpm install然后编译、运行即可。
约束与限制
兼容性
本文档内容基于以下版本验证通过:
- RNOH: 0.82.1; SDK: HarmonyOS 6.0.1 Release SDK; IDE: DevEco Studio 6.0.1 Release; ROM:6.0.0.120 SP7;
- RNOH: 0.77.18; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
使用示例
下面的代码展示了这个库的基本使用场景:
[!WARNING] 使用时 import 的库名不变。
import React from 'react';
import { Button, View } from 'react-native';
import RNShare from 'react-native-share';
function App() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>
<Button
title="测试RNShare.open"
onPress={async () => {
try {
const res = await RNShare.open({
title: '测试ShareOpenResult结构',
message: '测试内容',
url: 'https://www.baidu.com/',
});
} catch (error) {
console.log('###TestShareOpenResultError', JSON.stringify(error));
}
}}
/>
</View>
);
}
export default App;使用说明
open(打开系统分享面板)
import RNShare from 'react-native-share';
RNShare.open({
message: '分享一段文本',
title: '分享标题',
url: 'https://example.com', // 分享链接
urls: ['https://example.com/image.png'], // 分享多个链接(如图片)
type: 'image/jpeg', // MIME 类型
subject: '分享摘要', // 分享内容摘要
filename: 'my-image', // 文件名
filenames: ['image1', 'image2'], // 多文件
failOnCancel: false, // 取消分享时是否抛出异常
saveToFiles: false, // 是否保存分享文件到本地
excludedActivityTypes: ['0', '1'], // 排除的系统分享操作(0:复制到剪切板, 1:保存到媒体库, 2:保存到文件管理器, 3:打印, 4:保存到中转站)
}).then((result) => {
if (!result.success) {
console.log('用户取消分享');
return;
}
console.log('分享成功', result);
}).catch((error) => {
console.log('分享失败:', error.message);
});shareSingle(分享到指定应用)
HarmonyOS 目前仅支持 EMAIL 和 SMS
import RNShare from 'react-native-share';
// 分享到短信
RNShare.shareSingle({
social: RNShare.Social.SMS,
message: '这是一条分享消息',
url: 'https://example.com',
recipient: '123456789', // 收件人号码
subject: '分享主题', // 内容摘要
email: '', // 邮箱地址(仅 EMAIL 时有效)
}).then((result) => {
console.log('分享结果:', result.success, result.message);
});
// 分享到邮件
RNShare.shareSingle({
social: RNShare.Social.EMAIL,
subject: '邮件主题',
message: '邮件正文内容',
email: '[email protected]',
urls: ['https://example.com/image.png'], // 分享附件
}).then((result) => {
console.log('分享结果:', result.success, result.message);
});接口说明
[!TIP] "Platform"列表示该属性在原三方库上支持的平台。
[!TIP] "OpenHarmony Support"列为 yes 表示 OpenHarmony平台支持 该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。
API
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | Social | 支持分享的三方APP名称 | object | yes | iOS,Android | partially | | open: (options: ShareOptions) => Promise<ShareOpenResult> | 系统分享 | function | yes | iOS,Android | yes | | shareSingle: (options: ShareSingleOptions) => Promise<ShareSingleResult> | 三方APP分享 | function | yes | iOS,Android | partially | | isPackageInstalled: (packagename: string) => Promise <IsPackageInstalledResult> | 三方APP是否已在本机安装 | function | yes | iOS,Android | no |
ShareOptions :系统分享参数
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- |------------------------------------------------------------------------------------------------| ---- | -------- | -------- |-----------------------------------------| | type | 分享路径资源类型Mime Type | string | no | iOS,Android | yes | | urls | 分享多个路径 | string[] | no | iOS,Android | yes | | url | 分享路径 | string | no | iOS,Android | yes | | filename | 分享路径文件名 | string | no | iOS,Android | yes | | filenames | 分享多个路径的文件名(不带后缀,如123,要与urls对应) | Array | no | iOS,Android | yes | | message | 分享短信消息文本 | string | no | iOS,Android | partially(只支持系统分享面板,不支持分享面板底部选择应用后的分享) | | title | 分享标题 | string | no | iOS,Android | partially(只支持系统分享面板,不支持分享面板底部选择应用后的分享) | | subject | 分享内容摘要 | string | no | iOS,Android | partially(只支持系统分享面板,不支持分享面板底部选择应用后的分享) | | email | 收件人邮箱地址 | string | no | iOS,Android | no | | recipient | 接收短信消息的号码 | string | no | iOS,Android | no | | excludedActivityTypes | 系统分享面板操作区不应显示的能力列表(harmonyOS中传参例如['0','1'],对应解释为: 0:复制到剪切板,1:保存到媒体库,2:保存到文件管理器 ,3:打印,4:保存到中转站) | ActivityType[] | string[] | no | iOS,Android | partially | | failOnCancel | 分享失败的是否抛出异常 | boolean | no | iOS,Android | yes | | showAppsToView | 是否显示可以预览分享文件的APP | boolean | no | Android | no | | saveToFiles | 是否保存分享的路径文件到本地 | boolean | no | iOS,Android | yes | | activityItemSources | 系统分享面板中自定义分享数据 | ActivityItemSource[] | no | iOS | no | | isNewTask | 是否开启Activity的启动模式FLAG_ACTIVITY_NEW_TASK | boolean | no | Android | no |
ShareSingleOptions :三方APP分享参数
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- |-----------------------------------------------------------| ---- | -------- | -------- |-------------------| | social | 分享的三方APP名称 | string | yes | iOS,Android | partially | | appId | 三方APP上架市场的appid(social为instagramstories,facebookstories时必传) | string | no | iOS,Android | no | | type | 分享路径资源类型Mime Typ | string | no | iOS,Android | no | | urls | 分享多个路径 | string[] | no | iOS,Android | yes | | url | 分享路径 | string | no | iOS,Android | yes | | filename | 分享路径文件名(不带后缀,如 123) | string | no | iOS,Android | no | | message | 分享短信消息文本 | string | no | iOS,Android | yes | | title | 分享标题 | string | no | iOS,Android | no | | subject | 分享内容摘要 | string | no | iOS,Android | yes | | email | 收件人邮箱地址 | string | no | iOS,Android | yes | | recipient | 接收短信消息的号码 | string | no | iOS,Android | yes | | forceDialog | 是否开启三方分享对话框 | boolean | no | Android | no | | backgroundImage | 背景图像(social为instagramstories,facebookstories传参) | string | no | iOS,Android | no | | stickerImage | 贴纸图像(social为instagramstories,facebookstories传参) | string | no | iOS,Android | no | | backgroundBottomColor | 背景底部颜色(social为instagramstories,facebookstories传参) | string | no | iOS,Android | no | | backgroundTopColor | 背景顶部颜色(social为instagramstories,facebookstories传参) | string | no | iOS,Android | no | | attributionURL | 属性路径(social为instagramstories,facebookstories传参) | string | no | iOS,Android | no | | backgroundVideo | 背景视频(social为instagramstories,facebookstories传参) | string | no | iOS,Android | no | | linkUrl | 用作共享内容中链接的 URL(social为instagramstories) | string | no | iOS,Android | no | | linkText | 用作共享内容中链接的文本(social为instagramstories) | string | no | iOS,Android | no |
Social:可支持的三方APP种类
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- |-------------------| | FACEBOOK | facebook | string | yes | iOS,Android | no | | FACEBOOK_STORIES | facebookstories | string | yes | iOS,Android | no | | PAGESMANAGER | pagesmanager | string | yes | iOS,Android | no | | TWITTER | twitter | string | yes | iOS,Android | no | | WHATSAPP | whatsapp | string | yes | iOS,Android | no | | WHATSAPPBUSINESS | whatsappbusiness | string | yes | iOS,Android | no | | INSTAGRAM | instagram | string | yes | iOS,Android | no | | INSTAGRAM_STORIES | instagramstories | string | yes | iOS,Android | no | | GOOGLEPLUS | googleplus | string | yes | iOS,Android | no | | EMAIL | email | string | yes | iOS,Android | yes | | PINTEREST | pinterest | string | yes | iOS,Android | no | | LINKEDIN | linkedin | string | yes | iOS,Android | no | | SMS | sms | string | yes | iOS,Android | yes | | TELEGRAM | telegram | string | yes | iOS,Android | no | | SNAPCHAT | snapchat | string | yes | iOS,Android | no | | MESSENGER | messenger | string | yes | iOS,Android | no | | VIBER | viber | string | yes | iOS,Android | no | | DISCORD | discord | string | yes | iOS,Android | no |
ShareAsset :分享图片、视频数据枚举
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | BackgroundImage | social为instagramstories,facebookstories时分享的图片 | enum | no | no,Android | no | | BackgroundVideo | social为instagramstories,facebookstories时分享的视频 | enum | no | no,Android | no | | StickerImage | social为instagramstories,facebookstories时分享的贴纸图 | enum | no | no,Android | no | | BackgroundAndStickerImage | social为instagramstories,facebookstories时分享的背景贴纸 | enum | no | iOS,Android | no |
ActivityType:系统分享面板上支持的分享操作
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | ActivityType | default | addToReadingList | airDrop | assignToContact | copyToPasteBoard | mail | message | openInIBooks | postToFacebook | postToFlickr | postToTencentWeibo | postToTwitter | postToVimeo | postToWeibo | print | saveToCameraRoll | markupAsPDF | string | no | iOS,Android | no |
ShareSingleResult:调用三方分享接口返回的数据类型
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | message | 返回的消息 | string | yes | iOS,Android | yes | | success | 是否成功 | boolean | yes | iOS,Android | yes |
ShareOpenResult: 调用系统分享接口返回的数据类型
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- |-------------------| | message | 返回的消息 | string | yes | iOS,Android | yes | | success | 是否成功 | boolean | yes | iOS,Android | yes | | dismissedAction | 是否关闭或取消了分享弹窗 | boolean | no | iOS,Android | yes |
IsPackageInstalledResult:调用是否安装三方应用接口返回的数据类型
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- |-------------------| | message | 返回的消息 | string | yes | iOS,Android | no | | isInstalled | 三方APP是否已安装 | boolean | yes | iOS,Android | no |
ActivityItem:系统面板分享类型
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | type |活动面板类型 text | url | string | yes | iOS | no | | content | 内容 | string | yes | iOS | no |
LinkMetadata:系统分享中自定义分享操作的元数据
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- |-------------------| ---- | -------- | -------- | ------------------ | | originalUrl | 元数据请求的原始URL | string | no | iOS | no | | url | 元数据的URL | string | no | iOS | no | | title | URL代表的标题 | string | no | iOS | no | | icon | URL代表的icon | string | no | iOS | no | | image | URL的代表性图像数据 | string | no | iOS | no | | remoteVideoUrl | URL的代表视频相对应的远程URL | string | no | iOS | no | | video | URL的代表视频数据 | string | no | iOS | no | | base64Icon | 用于Base64 图像数据显示图标 | string | no | iOS | no |
ActivityItemSource:系统分享中自定义分享数据
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | placeholderItem | 分享数据的占位显示数据 | ActivityItem | yes | iOS | no | | item | 分享操作项 | ActivityItem | yes | iOS | no | | subject | 分享内容 | string | no | iOS | no | | dataTypeIdentifier | 数据类型标识符 | string | no | iOS | no | | thumbnailImage | 分享数据的缩略图 | string | no | iOS | no | | linkMetadata | 分享的数据 | LinkMetadata | no | iOS | no |
属性
Overlay:分享面板弹窗组件
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | visible | 是否显示 | boolean | yes | iOS,Android | yes | | children | JSX element | React.ReactNode | yes | iOS,Android | yes |
Button:分享按钮
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- |-------------| ---- | -------- | -------- | ------------------ | | onPress | 按压事件回调 | function | yes | iOS,Android | yes | | iconSrc | icon属性 | ImageSourcePropType | yes | iOS,Android | yes | | buttonStyle | button属性 | ViewStyle | no | iOS,Android | yes | | textStyle | text属性 | TextStyle | no | iOS,Android | yes | | children | JSX element | React.ReactNode | yes | iOS,Android | yes |
ShareSheet:分享面板组件
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | visible | 是否显示 | boolean | yes | iOS,Android | yes | | onCancel | 关闭面板的回调函数 | function | yes | iOS,Android | yes | | style | 分享面板中Sheet的CSS属性 | ViewStyle | no | iOS,Android | yes | | overlayStyle | 分享面板CSS属性 | ViewStyle | no | iOS,Android | yes | | children | JSX element | React.ReactNode | yes | iOS,Android | yes |
Sheet:分享面板组件的子组件,ShareSheet包含Sheet
| Name | Description | Type | Required | Platform | HarmonyOS Support | | ---- | ----------- | ---- | -------- | -------- | ------------------ | | visible | 是否显示 | boolean | yes | iOS,Android | yes | | children | JSX element | React.ReactNode | yes | iOS,Android | yes |
遗留问题
- [ ] 无法分享三方APP问题:issue#1
其他
目录结构
/rntpc_react-native-share # 项目根目录
├── harmony # 鸿蒙适配代码
│ ├── react_native_share.har # har 包
│ └── react_native_share/ # 鸿蒙适配核心代码
│ └── src/
│ └── main/
│ ├── cpp/ # C++ 原生模块
│ │ ├── CMakeLists.txt
│ │ ├── RNShare.cpp
│ │ ├── RNShare.h
│ │ └── RNSharePackage.h
│ └── ets/ # ArkTS 核心实现代码
│ ├── RNSharePackage.ets
│ ├── RNShareTurboModule.ts
│ ├── Types.ts
│ ├── utils/
│ │ ├── FileUtils.ts
│ │ └── Logger.ts
│ └── share/ # 各平台分享实现
│ ├── Share.ts
│ ├── ShareBaseInstance.ts
│ ├── shareMediaObject/ # 分享媒体对象
│ │ ├── MediaObject.ts
│ │ ├── MultiImageObject.ts
│ │ ├── ShareMediaObject.ts
│ │ ├── SuperGroupObject.ts
│ │ ├── TextObject.ts
│ │ ├── VideoSourceObject.ts
│ │ ├── WebPageObject.ts
│ │ └── WeiboMultiMessage.ts
│ ├── DiscordShare.ts
│ ├── DouyinShare.ts
│ ├── EmailShare.ts
│ ├── FacebookShare.ts
│ ├── FacebookStoriesShare.ts
│ ├── GenericShare.ts
│ ├── GooglePlusShare.ts
│ ├── InstagramShare.ts
│ ├── InstagramStoriesShare.ts
│ ├── LinkedinShare.ts
│ ├── MessengerShare.ts
│ ├── PinterestShare.ts
│ ├── SMSShare.ts
│ ├── SnapChatShare.ts
│ ├── TelegramShare.ts
│ ├── TwitterShare.ts
│ ├── ViberShare.ts
│ ├── WeiboShare.ts
│ ├── WhatsAppBusinessShare.ts
│ └── WhatsAppShare.ts
├── src # RN 代码
│ ├── index.tsx # 入口文件
│ ├── types.ts # 类型定义
│ ├── codegenSpec/
│ │ └── NativeRNShare.ts # Codegen 规范
│ ├── components/
│ │ ├── Button.tsx
│ │ ├── Overlay.tsx
│ │ ├── ShareSheet.tsx
│ │ └── Sheet.tsx
│ └── helpers/
│ ├── android.ts
│ ├── checkPermissions.ts
│ ├── options.ts
│ └── platform.ts
├── example/ # 示例项目
├── README.md # 中文安装使用方法
├── README_en.md # 英文安装使用方法
├── README.OpenSource # 开源说明
├── CHANGELOG.md # 更新日志
├── LICENSE # 开源协议贡献代码
使用过程中发现任何问题都可以提交 Issue,当然,也非常欢迎提交 PR 。
开源协议
本项目基于 The MIT License (MIT) ,请自由地享受和参与开源。
