React Native EP.2 QR Code Scanner App

ThanapongNoom
2 min readNov 5, 2019

--

สวัสดีครับตอนนี้ก็เป็นตอนที่ 2 ของผมนะครับ ไม่ขอเกริ่นอะไรมากมายนะครับ ก็เข้าเรื่องเลยเเล้วกัน

ตัวอย่าง QR code

สำหรับการทำ Application สเเกน QRcode นะครับ เครื่องมือที่ผมใช้ก็คือ react-native-qrcode-scanner อ้างอิง https://github.com/moaazsidat/react-native-qrcode-scanner

โดยการติดตั้งนะครับ เราสามาใช้คำสั่งติดตั้งตามด้านล่างได้เลยนะครับ

npm install react-native-qrcode-scanner --save

จากนั้นให้ใช้คำสั่งด้านล่างนี้เพื่อเชื่อมเครื่องมือที่เราใช้เข้ากับ project

***ถ้าพึ่งติดตั้ง react-native เพราะ version ใหม่ไม่ต้องใช้ link เเล้วครับ

react-native link react-native-qrcode-scanner

จากนั้นสร้าง function เพื่อขอใช้กล้อง

PermissionsStorage = async () => {const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA,{'title': 'ขออนุญาติใช้กล้อง','message': 'ระบบต้องการใช้กล้อง'})if (granted === PermissionsAndroid.RESULTS.GRANTED) {console.log("คุณสามารถใช้กล้องได้");} else {console.log("คุณไม่สามารถใช้กล้องได้");}}

เเละนี่คือ Code ทั้งหมด โดยการทำงานคือ Application จะสเเกนได้เเค่ QR code ที่เป็น Link URL เเล้วเปิด URL นั้น

import React, { Component } from 'react';

import {
AppRegistry,
StyleSheet,
Text,
NavigatorIOS,
TouchableOpacity,
Linking,
} from 'react-native';

import QRCodeScanner from 'react-native-qrcode-scanner';

class ScanScreen extends Component {
PermissionsStorage = async () => {const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA, { 'title': 'ขออนุญาติใช้กล้อง', 'message': 'ระบบต้องการใช้กล้อง' })if (granted === PermissionsAndroid.RESULTS.GRANTED) { console.log("คุณสามารถใช้กล้องได้");} else { console.log("คุณไม่สามารถใช้กล้องได้");}} onSuccess(e) {
Linking.openURL(e.data).catch(err => console.error('An error occured', err));
}
async componentDidMount(){ PermissionsStorage();}render() { return ( <QRCodeScanner onRead={this.onSuccess.bind(this)} topContent={ <Text style={styles.centerText}> Go to
<Text style={styles.textBold}>
wikipedia.org/wiki/QR_code
</Text>
on your computer and scan the QR code.
</Text> } bottomContent={ <TouchableOpacity style={styles.buttonTouchable}> <Text style={styles.buttonText}>OK. Got it!</Text> </TouchableOpacity> } /> );}}const styles = StyleSheet.create({ centerText: { flex: 1, fontSize: 18, padding: 32, color: '#777', }, textBold: { fontWeight: '500', color: '#000', }, buttonText: { fontSize: 21, color: 'rgb(0,122,255)', }, buttonTouchable: { padding: 16, },});

หน้าตาเมื่อ Run code

อ้างอิง https://www.npmjs.com/package/react-native-qrcode-scanner

--

--