react-native-share是用于社交分享的一个库
接下来介绍一下他的使用和出现的问题
npm i react-native-share
如果安装后出现项目无法启动,报错:
/Users/landsky/Desktop/xcodeworkspace/react-native/landsk2/node_modules/react-native-share/android/src/main/java/cl/json/social/TargetChosenReceiver.java:50: 错误: 找不到符号
这个错误是由于 Context.RECEIVER_EXPORTED 在某些 Android 版本中不可用。你可以通过修改 TargetChosenReceiver.java 文件来解决这个问题。将 Context.RECEIVER_EXPORTED 替换为 0。
使用:
import React, { useState } from 'react';
import { Button, View, TextInput } from 'react-native';
import Share from 'react-native-share';
const ShareExample = () => {
const [textToShare, setTextToShare] = useState('');
const onShare = async () => {
try {
const result = await Share.open({
message: textToShare,
url: 'https://example.com', // 可选,如果你想分享一个链接
title: '分享示例', // 在某些应用中可能会用作分享的标题
subject: '分享的内容', // 邮件应用中的主题
});
if (result.action === Share.sharedAction) {
console.log('分享成功');
} else if (result.action === Share.dismissedAction) {
console.log('用户取消了分享');
}
} catch (error) {
console.log(error.message, error.code);
}
};
return (
<View style={{marginTop:100}}>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={setTextToShare}
value={textToShare}
placeholder="输入要分享的内容"
/>
<Button title="分享" onPress={onShare} />
</View>
);
};
export default ShareExample;