【问题标题】:React Native QR scanner not scanningReact Native QR扫描仪不扫描
【发布时间】:2017-08-01 11:25:20
【问题描述】:

我正在尝试在 react native 中为 android 构建一个 QR 扫描仪。我有以下代码,但它不会扫描任何东西。为了让它工作,我需要在代码中做什么?

import React, { Component } from 'react';

import {
  AppRegistry,
  StyleSheet,
  View,
  Text,
  TouchableHighlight,
  TouchableOpacity,
  Image,
  Button
} from 'react-native';
import BarcodeScanner from 'react-native-barcodescanner';

export default class test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      torchMode: 'off',
      cameraType: 'back',
    };
  }

  barcodeReceived(e) {
    console.log('Barcode: ' + e.data);
    console.log('Type: ' + e.type);
  }

  render() {
    return (
      <View style={{flex: 1, flexDirection: 'row'}}>
      <BarcodeScanner
        onBarCodeRead={this.barcodeReceived}
        style={{ flex: 1 }}
        torchMode={this.state.torchMode}
        cameraType={this.state.cameraType}
      />
      </View>
    );
  }
}


AppRegistry.registerComponent('test', () => test);

How it looks on phone

【问题讨论】:

  • 在您的构造函数中添加this.barcodeReceived = this.barcodeReceived.bind(this),或更改您的函数声明以使用箭头函数,如下所示:barcodeReceived = (e) =&gt; {}。这与 React 中 this 的上下文有关。在没有绑定或使用箭头函数进行词法作用域的情况下,thisundefined

标签: react-native camera qr-code


【解决方案1】:

使用以便您可以对函数进行 bin 处理

onBarCodeRead={this.barcodeReceived.bind(this)}

也许这对你有帮助!!

【讨论】: