Last active
January 19, 2022 02:07
-
-
Save rs6000/b71940ecc701e3354b748768da191817 to your computer and use it in GitHub Desktop.
react native expo barcode module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment