React-Native調用系統分享組件Share組件的使用


title: React-Native調用系統分享Share組件的使用
tags: react-native


一. 方法

  • share
  • sharedAction
  • dismissedAction

二、具體說明

1.share
接口:
static share(content, options)

打開一個分享文本內容的對話框

  • 在 iOS 中,返回一個 Promise,最終會解析爲一個對象,包含有action和activityType兩個屬性。如果用戶取消對話框,則 Promise 仍將被解析,最終返回的action屬性會是Share.dismissedAction,而其他屬性爲 undefined。
  • 在 Android 中同樣返回一個 Promise,但返回的action始終爲Share.sharedAction。

In iOS, Returns a Promise which will be invoked an object containing action, activityType. If the user dismissed the dialog, the Promise will still be resolved with action being Share.dismissedAction and all the other keys being undefined.
In Android, Returns a Promise which always be resolved with action being Share.sharedAction.

Content參數說明
   - message - 要分享的消息
   - title - 消息的標題
   - url - 要分享的網址,(iOS系統中特有)

至少需要一個 url 和message。

options參數說明
ios
	- subject - 通過郵件分享的標題
	- excludedActivityTypes
	- tintColor
android
	- dialogTitle
2 sharedAction()
接口:
static sharedAction()

表示內容已成功分享。

3 dismissedAction()
接口:
static dismissedAction()

表示對話框被取消。僅限 iOS系統。

三. 效果如下所示

ios系統測試,調起系統分享

四、替代方案

我使用的rn版本是"react-native": “0.51.0”,在直接使用Share組件在android系統中,無法進行完成分享,每次分享都會出現無法獲取資源的問題,我在github中查看Share組件issue的時候,看到最新.53.0版本已經支持在安卓平臺的使用,請後期使用支持正版,哈哈哈,由於自己項目原因,於我還是使用用了下面這個庫:
react-native-share
這個庫能夠完美的支持分享功能,其中包括字符串分享、本地文件分享(圖片、pdf等)、遠程文件分享等功能.是一個很好的替代庫.
在使用分享文件時,需要注意option的參數設置,否則會將文件地址以字符串的形式分享出去:

 const shareOptions = {
      title: "React Native",
      type: 'application/pdf',
      url: `data:application/pdf;base64,${PDF_BASE64}`,
      showAppsToView: true,
    }

如上面代碼所示,分享pdf的時候,需要添加**type: ‘application/pdf’**字段的值.url可以按照下面這種形式添加:

url: "file:///storage/emulated/0/demo/test.pdf"

在最新版本中使用時,也會出現這種問題,可參考:
https://github.com/react-native-community/react-native-share/issues/718#issuecomment-601244491

至此完成分享功能的說明.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章