this is qrcode scanner.
npm install sg-rn-qr-scanner一个react-native的二维码扫描组件,支持扫描区域的限制以及扫描区域的偏移。
bash
yarn add react-native-camera react-native-qr-scanner
`$3
`bash
react-native link react-native-camera && react-native-qr-scanner
`$3
- ios在 ios/projectName/Info.plist:
`xml
NSCameraUsageDescription
NSPhotoLibraryUsageDescription
NSMicrophoneUsageDescription
NSPhotoLibraryAddUsageDescription
`
- android在 android/app/src/main/AndroidManifest.xml:
`xml
`#### 修复相机组件找不到google()方法的错误
https://github.com/react-native-community/react-native-camera/blob/master/docs/GradleUpgradeGuide.md
使用组件
$3
`javascript
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import {QRscanner} from 'react-native-qr-scanner';export default class Scanner extends Component {
constructor(props) {
super(props);
this.state = {
flashMode: false,
zoom: 0.2
};
}
render() {
return (
);
}
bottomView = ()=>{
return(
this.setState({flashMode:!this.state.flashMode})}>
点我开启/关闭手电筒
);
}
onRead = (res) => {
console.log(res);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000'
}
});
`$3
`javascript
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import {QRreader} from 'react-native-qr-scanner';
import ImagePicker from 'react-native-image-picker';export default class Scanner extends Component {
constructor(props) {
super(props);
this.state = {
reader: {
message: null,
data: null
}
};
}
render() {
return (
{
this.openPhoto();
}}>
打开相册识别二维码
{!this.state.reader? {!this.state.reader.message?'':
${this.state.reader.message}}: {!this.state.reader.message?'': ${this.state.reader.message}:${this.state.reader.data}}}
);
}
openPhoto(){
console.log('ImagePicker');
ImagePicker.launchImageLibrary({}, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
if(response.uri){
var path = response.path;
if(!path){
path = response.uri;
}
QRreader(path).then((data)=>{
this.setState({reader: {
message: '识别成功',
data: data
}});
// 十秒后自动清空
setTimeout(() => {
this.setState({reader: {
message: null,
data: null
}})
}, 10000);
}).catch((err)=>{
this.setState({reader: {
message: '识别失败',
data: null
}});
});
}
}
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
}
});
`运行示例
`bash
$ cd example
$ yarn
$ react-native run-ios 或者 $ react-native run-android
``