import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { Camera } from 'expo-camera';
export const QRCodeScanner = () => {
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [scanned, setScanned] = useState(false);
const [text, setText] = useState('');
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ data }) => {
setScanned(true);
setText(data);
};
const askForPermission = async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
};
if (hasPermission === null) {
// Camera permissions are still loading.
return <View />;
}
if (!hasPermission) {
// Camera permissions are not granted yet.
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center' }}>
We need your permission to show the camera
</Text>
<Button onPress={askForPermission} title="Grant Permission" />
</View>
);
}
const toggleFacing = () => {
setType(type === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back);
};
return (
<View style={styles.container}>
<Camera
style={styles.camera}
type={type}
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
/>
{scanned && (
<View style={styles.textContainer}>
<Text style={styles.text}>QR Code scanned:</Text>
<Text style={styles.scannedText}>{text}</Text>
<Button title="Scan Again" onPress={() => setScanned(false)} />
</View>
)}
<Button title="Toggle Facing" onPress={toggleFacing} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-start',
},
camera: {
flex: 0.5,
},
textContainer: {
flex: 0.5,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 18,
margin: 10,
},
scannedText: {
fontSize: 16,
margin: 10,
},
});
当我给出这样的值时
type ={CameraConstants.Type.back}
,我收到此错误
类型错误:无法读取未定义的属性“类型”
当我给出这样的值时
type ={'back'}
,我收到此错误错误:
元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:对象。
我尝试了 consol log Constants 它返回未定义 我尝试了 consol log CameraConstants 它返回未定义 谁能帮我解决这个问题,或者告诉我其他制作二维码扫描仪的方法
expo-camera 已升级版本。因此,不要使用 Camera,而是尝试使用 CameraView。我用顺风来造型。
import * as React from "react";
import { CameraView } from "expo-camera";
import tw from "twrnc";
const Camera: React.FC = () => {
const cameraRef = React.useRef<CameraView>(null);
return (
<View style={tw`flex-1`}>
<CameraView
ref={cameraRef}
/>
</View>
);
}
export default Camera;