React Native 二维码识别

最近在做项目中用到了二维码识别, 记录下自己踩过的坑,只针对Android
通过Google搜索,发现 react-native-camera 支持条码,二维码识别,支持 IOS and Android。

安装依赖

yarn add react-native-camera
react-native link react-native-camera 

react-native run-android 你将会发现错误

* What went wrong:
A problem occurred evaluating project ':react-native-camera'.
> Could not find method compileOnly() for arguments [com.facebook.react:react-native:+] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

翻了翻 react-native-camera issue 找的解决办法
https://github.com/react-native-community/react-native-camera/issues/1490

让我们不得不升级 Gradle 版本 v2 -> v4, 升级前做好备份 😘

升级 Gradle

android\build.gradle

buildscript {
    dependencies {
        ......
        +++ classpath 'com.android.tools.build:gradle:3.0.1'  // 升级gradle依赖
        ......
    }
}

allprojects {
    repositories {
        ...............
        +++ google()
        +++ maven { url "https://jitpack.io" }   // react-native-camera 可能需要这个
        ................
    }
}

android/app/build.gradle

android {
++  compileSdkVersion 26
++  buildToolsVersion "26.0.2"
.....
      +++  targetSdkVersion 26
......
}
dependencies {
   ......
   +++ compile "com.android.support:appcompat-v7:26.1.0"
   .....
}

😀 compileSdk buildTools 自行下载安装,这样我们的项目就可以顺利编译成功

实现扫描二维码

import { RNCamera } from 'react-native-camera'

....

<RNCamera
  ref={ref => {
    this.camera = ref
  }}
  onBarCodeRead={(e) =>{ 
    // 处理扫描结果
    console.warn(e)
  }}
  type={RNCamera.Constants.Type.back}
  permissionDialogTitle={'Permission to use camera'}
  permissionDialogMessage={'We need your permission to use your camera phone'}
/>

....

想知道更多请参考 https://github.com/react-native-community/react-native-camera 🤡

    原文作者:本间麻衣子
    原文地址: https://www.jianshu.com/p/2289ddd231c7
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞