這是一個在Expo專案內使用Barcode 模組的範例
我學React Native的目標就是做一個進銷存的APP
條碼掃描的功能是必須的,今天這個範例讓我離目標更進一步
import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
export default function App() {
const [hasPermission, setHasPermission] = useState(null)
const [scanned, setScanned] = useState(false)
const [text, setText] = useState("Not yet scanned!")
const askForCameraPermission = () => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === "granted")
})()
}
// Request 相機使用權限
useEffect(() => {
askForCameraPermission()
}, []);
// 掃描處理區塊
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setText(data);
console.log("type: " + type + "\nData: " + data);
}
// 檢查權限 & 畫面渲染
if (hasPermission === null) {
return (
<View style={styles.container}>
<Text>Requesting for Camera permission!</Text>
</View>
)
} else if (hasPermission === false) {
return (
<View style={styles.container}>
<Text style={{ margin: 10 }}>No access to camera</Text>
<Button title={'Allow Camera'} onPress={() => askForCameraPermission()} />
</View>)
}
// main view
return (
<View style={styles.container}>
<View style={styles.barCodeBox}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{ width: 400, height: 400, }}
/>
</View>
<Text style={styles.mainText}>{text}</Text>
{scanned && <Button title={"Scanned again"} color="tomato" onPress={() => setScanned(false)} />}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
barCodeBox: {
backgroundColor: "tomato",
alignItems: "center",
justifyContent: "center",
width: 300,
height: 300,
overflow: "hidden",
borderRadius: 30,
},
mainText: {
fontSize: 16,
margin: 20,
}
});
範例 Source Code:
git clone https://smilehsu@bitbucket.org/smilehsu/yt_example_barcode0119.git