字节笔记本

2026年2月22日

使用 React Native Share 实现应用内容分享功能

本文介绍如何在 React Native 应用中使用 react-native-share 库实现内容分享功能,包括分享链接、媒体文件以及分享到特定社交平台。

引言

随着社交媒体应用的兴起,企业保持相关性并触达更广泛受众的需求再怎么强调也不为过。作为工程师,我们经常构建影响人们生活的产品。虽然我们的解决方案可能很棒,但将这些解决方案交到用户手中往往不仅仅是将它们发布到生产环境。

随着我们的应用程序变得更加互联,用户能够与其他应用程序(从而与其他受众)分享内容变得越来越重要。本文旨在向你展示如何在 React Native 驱动的应用程序中实现与其他应用程序的内容分享。

为什么需要分享功能

从用户的角度来看,与其他应用分享内容有助于他们:

  • 建立他们感兴趣的内容集合
  • 与他们在其他平台上的网络分享内容
  • 收藏和保存内容以便日后查找

从商业角度来看,用户从一个应用程序或社交网络分享内容到另一个应用程序会增加企业的知名度和受众。可以将其视为一种间接的口碑传播,从一个用户传播到他们的网络。分享的用户为应用程序的潜在用户打开了大门。

React Native 内置分享包

React Native 提供了一个支持其移动应用程序分享功能的包。让我们简要了解一下这个包。

javascript
import React from 'react';
import { Share, View, Button } from 'react-native';

const ShareExample = () => {
  const onShare = async () => {
    try {
      const result = await Share.share({
        message: 'React Native | A framework for building native apps using React',
      });
      if (result.action === Share.sharedAction) {
        if (result.activityType) {
          // shared with activity type of result.activityType
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
        // dismissed
      }
    } catch (error) {
      alert(error.message);
    }
  };

  return (
    <View style={{ marginTop: 50 }}>
      <Button onPress={onShare} title="Share" />
    </View>
  );
};

export default ShareExample;

share 方法接受两个参数:contentoptionscontent 有三个字段:messagetitleurlurl 字段仅在 iOS 上有效。

React Native 分享包的问题在于其功能相当有限。例如,你不能使用这个包轻松分享其他形式的数据,如 PDF 或音频文件。使用 React Native 的 share,你也不能分享到特定的社交应用——例如分享到 Instagram 快拍。

React Native Share 库

为了绕过这些限制,我们可以使用更强大的 React Native Share 包。

React Native Share 诞生于 React Native 不断增长的贡献者社区。它是一个支持与其他应用程序进行社交分享的包,并带有内置功能,例如在 Facebook 快拍和其他社交应用程序上分享 PDF 文件、图像等。

环境要求

  • Expo CLI
  • Node.js v12.0.0 或更高版本

运行 expo init <your_app_name> 开始创建项目。

分享链接

安装包后,运行 npm start,然后运行 npm run <os_name 例如 android> 启动应用程序。

让我们从简单的东西开始:分享链接。

javascript
import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View, Button } from "react-native";
import Share from "react-native-share";

const url = "https://awesome.contents.com/";
const title = "Awesome Contents";
const message = "Please check this out.";

const options = {
  title,
  url,
  message,
};

export default function App() {
  const share = async (customOptions = options) => {
    try {
      await Share.open(customOptions);
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
      <Button
        onPress={async () => {
          await share();
        }}
        title="Share"
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

首先,我们导入 React Native Share 包,然后定义三组选项:

  • title:发送到应用操作系统共享活动的标题
  • message:分享内容时包含消息的选项
  • url:我们想要分享的链接

然后,我们创建一个 share 函数,该函数处理调用 share 的 open 方法,并将 options 属性传递给此方法。接下来,我们将这个 share 函数传递给一个按钮。

分享媒体文件

接下来,让我们分享图像和 PDF 文件。要分享媒体文件,你需要分享文件的 base64 编码格式。

javascript
import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View, Button, Image } from "react-native";
import Share from "react-native-share";
import file from "./assets/base64";

const url = "https://awesome.contents.com/";
const title = "Awesome Contents";
const message = "Please check this out.";

const options = {
  title,
  url,
  message,
};

export default function App() {
  const [image, setImage] = React.useState(
    "file:///data/user/0/com.rnshare/cache/rn_image_picker_lib_temp_0f9dbf03-c89c-4728-a763-6b15e3752f8e.jpg"
  );

  const share = async (customOptions = options) => {
    try {
      await Share.open(customOptions);
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
      <Image
        source={{ uri: image }}
        style={{ ...styles.containerImg, ...styles.stretchImg }}
      />
      <View style={{ marginVertical: 5 }}>
        <Button
          onPress={async () => {
            await share();
          }}
          title="Share Text"
        />
      </View>
      <View style={{ marginVertical: 5 }}>
        <Button
          onPress={async () => {
            await share({
              title: "Sharing image file from awesome share app",
              message: "Please take a look at this image",
              url: file.img,
            });
          }}
          title="Share Image"
        />
      </View>
      <View style={{ marginVertical: 5 }}>
        <Button
          onPress={async () => {
            await share({
              title: "Sharing pdf file from awesome share app",
              message: "Please take a look at this file",
              url: file.pdf,
            });
          }}
          title="Share pdf"
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  containerImg: {
    paddingTop: 50,
    marginVertical: 20,
  },
  stretchImg: {
    width: 200,
    height: 200,
    resizeMode: "stretch",
  },
});

我们创建了两个按钮——一个用于分享图像,另一个用于在模拟器上分享编码的 PDF 文件。

当你点击Share Image按钮时,会显示一个包含支持分享的不同应用的 UI。然后你可以点击任何你想用来分享的应用。

需要注意的是,根据你要分享的文件类型,某些应用程序不会显示。例如,当你分享 PDF 文件时,照片应用程序不会显示在可分享目标列表中。

分享到特定应用程序

我们在这里只是浅尝辄止,React Native Share 包可以做很多事情。如果你的用例需要,你可以直接分享到特定的应用程序,例如 WhatsApp。

javascript
const singleShare = async (customOptions) => {
  try {
    await Share.shareSingle(customOptions);
  } catch (err) {
    console.log(err);
  }
};

然后在最后一个按钮下方添加代码:

javascript
<View style={{ marginVertical: 5 }}>
  <Button
    onPress={async () => {
      await singleShare({
        title: "Share via whatsapp",
        message: "some awesome dangerous message",
        url: file.pdf,
        social: Share.Social.WHATSAPP,
        whatsAppNumber: "9199999999",
        filename: file.pdf,
      });
    }}
    title="Share to whatsapp"
  />
</View>

我们访问 share 包上的 singleShare 方法,它接受与 open 方法类似的选项,并带有额外的属性。我们传递我们想要定位的社交应用,然后是 whatsAppNumber,最后传递我们想要分享的文件。

检测已安装的应用程序

在之前的代码中,我们假设用户已安装 WhatsApp。虽然考虑到它的下载量,这可能是真的,但作为工程师我们不能做这种假设。

如果我们想检测用户是否安装了某个应用怎么办?幸运的是,React Native Share 包为我们提供了一个有用的方法。

让我们通过重用我们的 WhatsApp 示例来看看它的实际应用,但首先确认用户已安装 WhatsApp。

javascript
const singleShare = async (customOptions) => {
  try {
    const { isInstalled } = await Share.isPackageInstalled(
      "com.whatsapp.android"
    );
    if (isInstalled) {
      await Share.shareSingle(customOptions);
    } else {
      Alert.alert(
        "Whatsapp not installed",
        "Whatsapp not installed, please install.",
        [{ text: "OK", onPress: () => console.log("OK Pressed") }]
      );
    }
  } catch (err) {
    console.log(err);
  }
};

我们首先使用 isPackageInstalled 方法检查是否安装了 WhatsApp,并传递应用程序的 ID。此 ID 必须是有效的 iOS 或 Android 应用程序 ID。然后,如果已安装,我们调用 singleShare 方法,否则我们提醒用户未安装 WhatsApp。

不幸的是,isPackageInstalled 方法仅适用于 Android,但你可以在 iOS 中使用 Linking.canOpenURL(<app_schema>) 检查应用程序是否安装在用户的设备上。

总结

我们已经走了很长的路!我们首先探索了 React Native 的内置 share 包,并研究了它的局限性。接下来,我们查看了 React Native Share 包以及它在分享各种类型的媒体与各种社交应用方面赋予我们的超能力。

我们可以对应用程序进行的一项改进是在初始渲染期间首先检测某些特定的社交应用(如 WhatsApp)是否安装在应用程序上,然后隐藏或显示Share to WhatsApp按钮。这提供了更好的用户体验。

需要注意的是,React Native Share 包尚不支持 Expo 管理的引导应用程序。此外,即使你在使用裸工作流,这也无法与 Expo Go 客户端一起使用。如果你的项目使用 Expo 并依赖于 Expo Go 客户端,你应该改用 Expo 分享包。

希望本文能帮助你理解如何在应用中启用分享功能。

参考链接

分享: