React Native之二维码扫描

来源:互联网 发布:淘宝订单处理流程 编辑:程序博客网 时间:2024/05/16 05:11

我们知道在Android原生开发中,我们经常要用到二维码扫描的功能,在微信、QQ、浏览器、名片全能王、淘宝、支付宝等等软件里面,都会用到,android里面我们最常用的就是zxing,而在RN里面也有类似的组件,感谢作者ideacreation/react-native-barcodescanner,刚好我的原项目里面有个二维码扫描付款的功能,现在我用RN来大致演示下如何扫描二维码,并把扫描后的结果传回给第一个页面。

一、新建一个项目,cd进入项目内,然后打开终端输入:npm i --save React-native-barcodescanner

二、等安装完毕后:输入 rnpm link;有些同学会提示找到不到rnpm这个命令,你有两种解决方案:

第一、输入 npm i -g rnpm --save先安装rnpm,然后再输入rnpm link自动添加依赖;

第二、不用安装rnpm,直接输入 react-native link,一样可以添加依赖。

三、然后把https://github.com/ideacreation/react-native-barcodescanner/blob/master/Examples/BarcodeScanner/index.android.js里面的内容拷贝到我们的项目里面,然后进行修改:

我的修改内容如下:


import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
 Text,
  Vibration,
  View
} from 'react-native';
import BarcodeScanner from 'react-native-barcodescanner';
export default class Barcode extends Component {
  constructor(props) {
    super(props);
    this.state = {
      barcode: '',
      cameraType: 'back',
      text: '扫描二维码',
      torchMode: 'off',
      type: '',
    };
  }


  barcodeReceived(e) {
    if (e.data !== this.state.barcode || e.type !== this.state.type) Vibration.vibrate();
    this.setState({
      barcode: e.data,
      text: `${e.data} (${e.type})`,
      type: e.type,
    });
    const {navigator}=this.props;
    if (this.props.getUrl) {
      let url = this.state.text;
      this.props.getUrl(url);
    }
    if (navigator) {
      navigator.pop({
        name:'barcode'
      })
    }
  }
  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>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  statusBar: {
    height: 100,
    alignItems: 'center',
    justifyContent: 'center',
  },
  statusBarText: {
    fontSize: 20,
  },
});

其中state里面的barcode是扫描后的数据;

cameraType是摄像机的类型,表示用前置摄像机还是后置摄像机;

text是扫描后的文本;

barcodeReceived(e)是扫描后接受的函数,接受参数为e,数据都在e里面,

我上面采用的是当接收到参数后,把这个text传递给第一个页面,同时把这个页面给pop掉,

第一个页面的内容如下:

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  Image,
  View,
  Dimensions,
  TouchableOpacity,
  Navigator
} from 'react-native';
const {width,height}= Dimensions.get('window');
import Barcode from './barcode';
class PurchaseMain extends Component {
  constructor(props) {
    super(props);


    this.state = {
      username:'无名氏',
      barcodeResult:''
    };
  }


  render() {
    return (
      <View style={styles.container}>
        <View style={styles.top}>
          <Image source={require('../../images/purchasetop.png')} style={styles.topimage}/>
          <Text style={{fontSize:14,color:'black'}}>{this.state.username}</Text>
        </View>
        <TouchableOpacity onPress={this.toBarCodePage} style={styles.centerbg}>
          <View >
          <Image source={require('../../images/purchasecenter.png')} style={styles.center}/>
          <Text style={{fontSize:12,color:'white'}}>付款扫描</Text>
          </View>
        </TouchableOpacity>
        <Text>这里是二维的结果:</Text>
        <Text>{this.state.barcodeResult}</Text>
      </View>
    );
  }
  toBarCodePage=()=>{
    const {navigator}=this.props;
    const self = this;
    if (navigator) {
      navigator.push({
        name:'barcode',
        component:Barcode,
        params:{
          //从详情页获取扫描的结果url
          getUrl:(url)=>{
            self.setState({
              barcodeResult:url
            })
          }
        }


      })
    }
  }
}
export default class Purchase extends Component{
  render(){
    return(
      <Navigator
      initialRoute={{name:'purchase',component:PurchaseMain}}
      renderScene={
            (route, navigator) =>
             {
            let Component = route.component;
            return <Component {...route.params} navigator={navigator} />
        }
      }/>
    )
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent:'center',
    alignItems:'center'
  },
  top:{
    position:'absolute',
    marginTop:-20,
    top:0,
    left:0,
    justifyContent:'center',
    alignItems:'center',
  },
  topimage:{
    resizeMode:'contain',
    height:height/3,
    width:width,
    marginBottom:10
  },
  centerbg:{
    position:'absolute',
    bottom:(width-150)/2,
    left:(width-150)/2,
    backgroundColor:'#ec6638',
    width:150,
    height:150,
    borderRadius:75,
    justifyContent:'center',
    alignItems:'center',


  },
  center:{
    width:60,
    height:60,
    marginBottom:10
  }
});


state里面的barcodeResult就是扫描的结果

大家可以上进我的github上,把这个工程下载下来,在android手机上运行下:

我的项目地址:https://github.com/LiuC520/react-native-jifenmao

下载运行步骤: 

1、先 Git clone https://github.com/LiuC520/React-Native-jifenmao 

2、cd React-Native-jifenmao

3、安装库文件:npm install

4、安装依赖:react-native link

5、react-native run-android 然后就可以运行了




0 0
原创粉丝点击