react-native android:实现二维码的扫描
请直接参考一下链接:
react-native 实现二维码的扫描功能 http://www.jianshu.com/p/2da8e08888e4
package.json参考:
"react": "16.0.0-alpha.6",
"react-native": "0.43.2",
"react-native-barcodescanner": "^3.1.1",
"react-native-camera": "^0.6.0",
既然是要调用硬件 API,那肯定有原生代码在里面,需要把原生模块给链接到相应的原生项目中。
这里既可以手动,又可以使用一个叫 rnpm 的工具。
rnpm 的全名是『React Native Package Manager』,高大上有木有,主要就是用来把一些 React Native 库中用到的原生模块给添加到相应的原生项目中。
安装比较简单:
npm install -g rnpm
链接:
npm install react-native-camera --save
npm install react-native-barcodescanner --save
rnpm link react-native-camera
rnpm link react-native-barcodescanner
还可以用手动链接的方法,参考:
https://github.com/lwansbrough/react-native-camera#manual-install
https://github.com/ideacreation/react-native-barcodescanner#installation
链接完成后会在android文件中出现如下内容:
在你的android/settings.gradle下面加上:
include ':react-native-camera'
project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android')
include ':react-native-barcodescanner'
project(':react-native-barcodescanner').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-barcodescanner/android')
3.在你的android/app/build.gradle加上这个依赖
dependencies{...
compile project(':react-native-camera')
compile project(':react-native-barcodescanner')
}
在你的MainApplication.java文件中加入:
开头:加上 import com.eguma.barcodescanner.BarcodeScannerPackage;
然后在这个: List getPackages() 方法中加上
new BarcodeScannerPackage()
要添加两个权限,一个是振动,一个是照相机
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.VIBRATE"/>
index.android.js
import React, {
Component
} from 'react';
import {
AppRegistry,
StyleSheet,
View,
Text,
Vibration
} from 'react-native';
import BarcodeScanner from 'react-native-barcodescanner';
class BarcodeScannerApp extends Component {
constructor(props) {
super(props);
this.state = {
barcode: '',
cameraType: 'back',
text: 'Scan Barcode',
torchMode: 'off',
type: '',
};
}
render() {
return (
<View style={styles.container}>
<BarcodeScanner
onBarCodeRead={this.barcodeReceived.bind(this)}
style={{flex:1}}
torchMode={this.state.torchMode}
cameraType={this.state.cameraType}
/>
<View style={styles.statusBar}>
<Text style={styles.statusBarText}>{this.state.text}</Text>
</View>
</View>
);
}
barcodeReceived(e) {
if (e.data !== this.state.barcode || e.type !== this.state.type) {
this.setState({
barcode: e.data,
text: `${e.data}(${e.type})`,
type: e.type,
});
}
}
}
var styles = StyleSheet.create({
container: {
flex: 1
},
statusBar: {
height: 100,
alignItems: 'center',
justifyContent: 'center',
},
statusBarText: {
fontSize: 20,
}
})
// 注册应用(registerComponent)后才能正确渲染
// 注意:只把应用作为一个整体注册一次,而不是每个组件/模块都注册
AppRegistry.registerComponent('AwesomeProject', () => BarcodeScannerApp);
扫描二维码显示效果如下:
参考链接:
http://www.imbeta.cn/react-native-shi-xian-er-wei-ma-sao-miao.html