React-Native 二维码扫码功能
在网上找了很多资料,没有找到纯净简单的代码,别人封装好的对于新人是不适合的
网上找了两个相关的库react-native-camera 和 react-native-barcodescanner ,看别人的博客讲react-native-camera 主要是用来调用摄像头的,Android iOS 都可以用,但是识别条形码的功能只有 ios 有,而react-native-barcodescanner 直接只支持 android,
后面发现了一个第三方 react-native-barcode-scanner-universal说是支持安卓和iOS,但是到目前只能iOS运行,Android不能运行原因还没找到,
最最最讨厌写博放代码不给全的人,所以以下代码是全部代码以及步骤:
-iOS端为例
1, 终端cd到项目目录下,运行一下以下命令
npm install react-native-camera 或 yarn add react-native-camera
npm install react-native-barcodescanner 或 yarn add react-native-barcodescanner
npm install -g rnpm
(***rnpm 的全名是『react native Package Manager』)
rnpm link react-native-camera
rnpm link react-native-barcodescanner
项目文件:
import React,{Component} from 'react';
import BarcodeScanner from 'react-native-barcode-scanner-universal'
import {
AppRegistry,
View,
Text,
StyleSheet,
Platform,
} from 'react-native';
export default class ScanCode extends Component {
static navigationOptions = {
headerTitle: '二维码扫码Demo',
};
constructor(props) {
super(props);
this.state = {
code: "None"
};
this._show = this._show.bind(this);
}
render() {
let scanArea = null;
if (Platform.OS === 'ios') {
scanArea = (
<View style={styles.rectangleContainer}>
<View style={styles.rectangle} />
</View>
)
}
return (
//官方demo上BarcodeScanner外面还包了层View,但是会有一个问题,看不到相机页面,但是扫码正常,后面我就直接把BarcodeScanner外层的View给掉了,结果就好了
<BarcodeScanner
onBarCodeRead={ (code) => this._show(code)}
style={styles.camera}>
//********相机页面添加组件在这里******
{scanArea}
</BarcodeScanner>
)
}
_show(val) {
this.setState({
code:val.data,
});
alert(val.data);
}
};
var styles = StyleSheet.create({
camera: {
flex: 1,
marginTop:0,
},
rectangleContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent'
},
rectangle: {
height: 250,
width: 250,
borderWidth: 2,
borderColor: '#00FF00',
backgroundColor:'transparent',
}
})
var Dimensions = require('Dimensions');
var widthd = Dimensions.get('window').width;
var height = Dimensions.get('window').height;
真机调试遇到的问题:
1.由于iOS涉及到相机权限获取问题,所以使用XCode打开项目后,在项目的Info.plist文件中添加
<key>NSPhotoLibraryUsageDescription</key>
<string>此 App 需要您的同意才能读取媒体资料库</string>
<key>NSCameraUsageDescription</key>
<string>cameraDesciption</string>
<key>NSContactsUsageDescription</key>
<string>contactsDesciption</string>
<key>NSMicrophoneUsageDescription</key>
<string>microphoneDesciption</string>
2.运行报错:Code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 8.0'
解决:给项目选择Team