推荐开源项目:react-native-qrcode-reader - 轻松实现React Native的二维码扫描器
import React, { useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { RNCamera } from 'react-native-camera';
import RNBarcodeScanner from 'react-native-barcodescanner';
export default function QRCodeScanner() {
useEffect(() => {
RNBarcodeScanner.requestCameraPermissions().then(
(granted) => {
if (granted) {
console.log('Camera permission granted');
// 扫描二维码
RNBarcodeScanner.scanBarcode().then(({ barcode }) => {
console.log('Barcode: ', barcode);
});
} else {
console.log('Camera permission not granted');
}
}
);
}, []);
return (
<View style={styles.container}>
<RNCamera
style={styles.preview}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.FlashMode.off}
androidCameraPermissionOptions={{
title: 'Permission to use camera',
message: 'We need your permission to use your camera.',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
androidRecordAudioPermissionOptions={{
title: 'Permission to use audio recording',
message: 'We need your permission to use your audio.',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
});
这个代码实例展示了如何在React Native应用中使用react-native-barcodescanner
库来扫描二维码。首先,它请求摄像头的权限,然后在获得权限后,开始预览摄像头并扫描二维码。扫描结果会在控制台输出。这个例子简洁明了,并且注重于实际的应用场景,是学习如何在React Native中实现二维码扫描的好例子。
评论已关闭