expoを利用すれば簡単にQR(Barcode)をリードできます。ちなみに生成はこちら。
実装
下記のように書けば動きます。
パーミッション取ったり。
App.js
import React from 'react';
import { StyleSheet, Text, View,Alert } from 'react-native';
import { BarCodeScanner, Permissions } from 'expo';
export default class App extends React.Component {
state = {
hasCameraPermission: null,
}
async componentDidMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted'
});
}
render() {
const { hasCameraPermission } = this.state;
if(hasCameraPermission === null){
return <Text>Requesting for camera permission</Text>
}
if(hasCameraPermission === false){
return <Text>No access to camera</Text>
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<BarCodeScanner
onBarCodeRead={this.handleBarCodeScanned}
style={{height:300, width:300}}
/>
</View>
);
}
handleBarCodeScanned = ({type, data}) => {
Alert.alert('barcode type:' + type + ' data: ' + data);
}
}
考察
- 読み取りを中止するコマンドが無いため、画面移動等、ずっと読み続けない実装が必要である。
- Androidでheightが効かない(伸びてしまう)。
- オーバーレイで読み取り範囲とかを表示するにはハック的対応が必要となる。
参考
下記に読み取り画面のスタイリングやキャンセル等のサンプルがある(未検証)。
画面制御によりQRの読み取り開始、終了を制御するサンプルを書きました(環境依存です。すみません)。