React Native使用react-native-share报null is not an object错误如何解决?
问题解决方案
1. 修复原生模块加载问题
当前报错的核心原因是react-native-share的原生模块未被正确加载到项目中,按你的RN版本对应处理:
- RN 0.60及以上版本(支持自动链接)
- 安卓:执行
npx react-native link react-native-share后,重新编译安卓项目 - iOS:进入项目ios目录,执行
pod install,完成后关闭Xcode重新打开项目并编译运行
- 安卓:执行
- RN 0.60以下版本
手动执行npx react-native link react-native-share后,分别校验安卓、iOS端的原生配置文件是否已引入RNShare相关项,确认无误后重新编译项目。
2. 修正组件语法错误
你的代码采用函数式组件写法,但错误使用了Class组件的this指向语法,会导致二维码实例无法正常获取,改用useRef钩子实现即可,修正后完整代码如下:
import { useRef } from 'react'; import { View, TouchableOpacity, Text, StyleSheet } from 'react-native'; import QRCode from 'react-native-qrcode-svg'; import Share from 'react-native-share'; export default function App() { const svgRef = useRef(null); const saveQRCode = () => { svgRef.current.toDataURL(callback); }; const callback = (dataURL) => { console.log(dataURL); const shareImageBase64 = { title: 'React Native', url: `data:image/png;base64,${dataURL}`, subject: 'Share Link', // 邮件分享专用字段 }; Share.open(shareImageBase64).catch(error => console.log(error)); }; return ( <View style={styles.container}> <QRCode value={JSON.stringify({test: 'testdata'})} getRef={c => (svgRef.current = c)} /> <TouchableOpacity onPress={saveQRCode}> <View style={styles.instructions}> <Text>Share QR code</Text> </View> </TouchableOpacity> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, instructions: { marginTop: 20, padding: 12, backgroundColor: '#eaeaea', borderRadius: 4, } });
3. 环境配置校验
- 安卓11及以上版本:需在
AndroidManifest.xml中添加对应分享平台的queries配置,避免系统拦截分享动作 - iOS端:若需分享到特定第三方平台,需在
Info.plist的LSApplicationQueriesSchemes字段下添加对应平台的白名单配置
所有修改完成后,完全关闭当前运行的项目实例,重新全量编译后再测试分享功能即可。
内容的提问来源于stack exchange,提问作者toni
相关产品推荐
相关产品推荐

