iOS・Androidのネイティブ機能をJavaScriptで操作する標準APIを使って、シェアボタンを実装する手順を紹介する。
Shareの基本的な使い方
Shareを利用することで、SNSやメール、Bluetoothを使ったファイルのコピーなど、スマホアプリでよく使われるシェア機能を実装することができる。
Share.share({ title: 'タイトル', message: '概要' }, {}).then((result, activityType) => { // 結果を受け取る })
サンプルコード
Shareを使ったサンプルコードがこちら。
import React, { Component } from 'react'; import { Text, View, Button, Share } from 'react-native'; export default class App extends Component { constructor(props) { super(props); } openShare() { Share.share({ title: 'タイトル', message: '概要' }, {}).then((result, activityType) => { if(result.action == Share.dismissedAction) { // シェアを中断した場合の処理(iOSのみ) } else if(result.action == Share.sharedAction) { // シェアを実行した場合(Androidの場合は常にここの処理が実行される) } else { } }); } render() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }}> <Button onPress={() => this.openShare()} title={'シェアする'} /> </View> ); } }
Expoで実機確認を行ってみよう。
アプリが起動すると画面中央にボタンが現れる。

ボタンをタップするとOS標準のシェアダイアログが表示される。
