使用react-native-qrcode-scanner报错:无法解析PermissionsAndroid模块
React Native 使用 react-native-qrcode-scanner 扫码报错解决
问题详情
我在React Native项目中尝试用react-native-qrcode-scanner包读取二维码,已通过npm install module@latest --save命令安装了react-native-camera和react-native-permissions依赖,但运行代码时出现以下错误:
ERROR in ./node_modules/react-native-camera/src/RNCamera.js:9:24 Module not found: Can't resolve 'react-native-web/dist/exports/PermissionsAndroid' 7 | NativeModules, 8 | ViewPropTypes, > 9 | requireNativeComponent, | ^ 10 | View, 11 | ActivityIndicator, 12 | Text, ERROR in ./node_modules/react-native-qrcode-scanner/index.js:4:35 Module not found: Can't resolve 'react-native-web/dist/exports/PermissionsAndroid' 2 | 3 | import React, { Component } from 'react'; > 4 | import PropTypes from 'prop-types'; | ^ 5 | 6 | import { 7 | StyleSheet, web compiled with 2 errors and 3 warnings
我的扫码组件代码示例:
import QRCodeScanner from 'react-native-qrcode-scanner'; const MyQRCodeScanner = () => { const onSuccess = (e) => { console.log(e.data); // e.data 为扫描到的二维码内容 }; return ( <QRCodeScanner onRead={onSuccess} /> ); };
解决方法
1. 修复依赖版本兼容问题
错误核心是react-native-qrcode-scanner与react-native-camera版本不匹配,且当前版本依赖了未安装的react-native-web模块。建议安装经过验证的兼容版本:
- 先卸载现有冲突依赖:
npm uninstall react-native-camera react-native-qrcode-scanner - 安装稳定兼容版本:
npm install react-native-camera@3.44.3 react-native-qrcode-scanner@1.5.5 --save
2. 处理Web环境适配(若需在Web端运行)
react-native-qrcode-scanner本身不支持Web环境,如果是在Web环境下编译运行,可选择:
- 切换到React Native原生环境(Android/iOS)运行项目
- 改用支持Web的扫码库,比如
@zxing/library - 若坚持使用当前库,需补充安装
react-native-web并配置polyfill:npm install react-native-web --save
3. 配置相机权限
确保项目已添加相机权限配置:
- Android:在
android/app/src/main/AndroidManifest.xml中添加:<uses-permission android:name="android.permission.CAMERA" /> - iOS:在
ios/[项目名]/Info.plist中添加:<key>NSCameraUsageDescription</key> <string>需要访问相机以扫描二维码</string>
4. 清除缓存并重新构建
执行以下命令清除缓存,避免旧依赖残留:
npm start --reset-cache # 重新运行对应平台 react-native run-android # 或 react-native run-ios
内容的提问来源于stack exchange,提问作者Arnaud Girard
相关产品推荐
相关产品推荐

