简体   繁体   English

如何在React原生中制作QR码扫描仪?

[英]How to make a QR code scanner in React native?

In my React native project, I am using expo to build an application which will scan QR code. 在我的React本机项目中,我使用expo来构建一个扫描QR码的应用程序。 for that reason I have installed the following package using this command- 因为这个原因我使用这个命令安装了以下包 -

npm install expo-barcode-scanner npm install expo-barcode-scanner

I have followed the below example given in snack expo- 我已经按照下面的例子给出了小吃展示 -

https://snack.expo.io/BJlFFcp2g https://snack.expo.io/BJlFFcp2g

When I run this example on my device it works. 当我在我的设备上运行此示例时,它可以工作。

But in my React-native project, when I copy the same code given in App.js file, after running the application the camera opens but it shows no result while scanning. 但是在我的React原生项目中,当我复制App.js文件中给出的相同代码时,运行应用程序后相机会打开,但扫描时没有显示结果。

Here is the code- 这是代码 -

App.js App.js

import React, { Component } from 'react';
import { Alert, Linking, Dimensions, LayoutAnimation, Text, View, StatusBar, StyleSheet, TouchableOpacity } from 'react-native';
import { BarCodeScanner, Permissions } from 'expo';

export default class App extends Component {
  state = {
    hasCameraPermission: null,
    lastScannedUrl: null,
  };

  componentDidMount() {
    this._requestCameraPermission();
  }

  _requestCameraPermission = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({
      hasCameraPermission: status === 'granted',
    });
  };

  _handleBarCodeRead = result => {
    if (result.data !== this.state.lastScannedUrl) {
      LayoutAnimation.spring();
      this.setState({ lastScannedUrl: result.data });
    }
  };

  render() {
    return (
      <View style={styles.container}>

        {this.state.hasCameraPermission === null
          ? <Text>Requesting for camera permission</Text>
          : this.state.hasCameraPermission === false
              ? <Text style={{ color: '#fff' }}>
                  Camera permission is not granted
                </Text>
              : <BarCodeScanner
                  onBarCodeRead={this._handleBarCodeRead}
                  style={{
                    height: Dimensions.get('window').height,
                    width: Dimensions.get('window').width,
                  }}
                />}

        {this._maybeRenderUrl()}

        <StatusBar hidden />
      </View>
    );
  }

  _handlePressUrl = () => {
    Alert.alert(
      'Open this URL?',
      this.state.lastScannedUrl,
      [
        {
          text: 'Yes',
          onPress: () => Linking.openURL(this.state.lastScannedUrl),
        },
        { text: 'No', onPress: () => {} },
      ],
      { cancellable: false }
    );
  };

  _handlePressCancel = () => {
    this.setState({ lastScannedUrl: null });
  };

  _maybeRenderUrl = () => {
    if (!this.state.lastScannedUrl) {
      return;
    }

    return (
      <View style={styles.bottomBar}>
        <TouchableOpacity style={styles.url} onPress={this._handlePressUrl}>
          <Text numberOfLines={1} style={styles.urlText}>
            {this.state.lastScannedUrl}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.cancelButton}
          onPress={this._handlePressCancel}>
          <Text style={styles.cancelButtonText}>
            Cancel
          </Text>
        </TouchableOpacity>
      </View>
    );
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#000',
  },
  bottomBar: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: 'rgba(0,0,0,0.5)',
    padding: 15,
    flexDirection: 'row',
  },
  url: {
    flex: 1,
  },
  urlText: {
    color: '#fff',
    fontSize: 20,
  },
  cancelButton: {
    marginLeft: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  cancelButtonText: {
    color: 'rgba(255,255,255,0.8)',
    fontSize: 18,
  },
});

So, I am not getting - what should I do to make the QR code scanner working? 所以,我没有得到 - 我应该怎么做才能使QR码扫描仪工作? It would be very nice if someone suggests me to solve this or give me any example so that I can implement this. 如果有人建议我解决这个问题或给我任何一个例子以便我能够实现这一点,那将是非常好的。

I personally have had more success using the library at https://github.com/moaazsidat/react-native-qrcode-scanner for QR code scanning. 我个人在https://github.com/moaazsidat/react-native-qrcode-scanner上使用该库获得了更多成功,用于QR码扫描。 Giving this a try may solve your problem? 尝试一下可能会解决您的问题? They have a getting started in the README that I recommend following in this case. 他们在自述文件中有一个入门,我建议在这种情况下使用它。

This is the code of my QR scanner 这是我的QR扫描仪的代码

import React, { Component } from 'react';
import { Alert, View, Text, Vibration, StyleSheet } from 'react-native';
import { Camera, BarCodeScanner, Permissions } from 'expo';

export default class ExpoScanner extends Component {
  constructor(props) {
    super(props);


    this.onBarCodeRead = this.onBarCodeRead.bind(this);
    this.renderMessage = this.renderMessage.bind(this);
    this.scannedCode = null;

    this.state = {
      hasCameraPermission: null,
      type: Camera.Constants.Type.back,
      id_cedulacli: '',
            placa:'',
            monto:'', 
            fecha_pago:'Seleccione fecha'   
    };
  }

  async componentWillMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    await this.setState({hasCameraPermission: status === 'granted'});
    await this.resetScanner();
  }

  multaEdit = ({data, type}) =>{

    if ((type === this.state.scannedItem.type && data === this.state.scannedItem.data) || data === null) {
      return;
    }

    this.setState({ scannedItem: { data, type } });

    const {placa} = this.state;
    const {monto} = this.state;
    const {fecha_pago} = this.state;

    Vibration.vibrate();

    console.log(`EAN scanned: ${data}`);


  fetch('http://10.10.20.88/parciall/editarMul.php', {
    method: 'post',
    header:{
      'Accept': 'application/json',
      'Content-type': 'application/json'
    },          
    body:JSON.stringify({
      placa: placa,
      monto: monto,
      id_cedulacli: ''+`${data}`,
      fecha_pago: fecha_pago,
    })

  })
  .then((response) => response.json())
    .then((responseJson) =>{
      if(responseJson == "Actualización completada"){
        alert(responseJson);
        this.props.navigation.navigate("InicioScreen");
      }else{

        alert(responseJson);

      }             

          })

    .catch((error)=>{
      console.error(error);
    });

    this.props.navigation.navigate('Inicio', { ean: data });

  }

  renderAlert(title, message) {
    Alert.alert(
      title,
      message,
      [
        { text: 'OK', onPress: () => this.resetScanner() },
      ],
      { cancelable: true }
    );
  }

  onBarCodeRead({ type, data } ) {
    if ((type === this.state.scannedItem.type && data === this.state.scannedItem.data) || data === null) {
      return;
    }

    Vibration.vibrate();
    this.setState({ scannedItem: { data, type } });

      console.log(`EAN scanned: ${data}`);
  }

  renderMessage() {
    if (this.state.scannedItem && this.state.scannedItem.type) {
      const { type, data } = this.state.scannedItem;
      return (
        <Text style={styles.scanScreenMessage}>
          {`Scanned \n ${type} \n ${data}`}
        </Text>
      );
    }
    return <Text style={styles.scanScreenMessage}>Focus the barcode to scan.</Text>;
  }

  resetScanner() {
    this.scannedCode = null;
    this.setState({
      scannedItem: {
        type: null,
        data: null
      }
    });
  }

  render() {
    const { hasCameraPermission } = this.state;

    if (hasCameraPermission === null) {
      return <Text>Requesting for camera permission</Text>;
    }
    if (hasCameraPermission === false) {
      return <Text>No access to camera</Text>;
    }
    return (
      <View style={styles.container}>
        <View style={{ flex: 1 }}>
          <BarCodeScanner
            onBarCodeScanned={this.multaEdit}
            style={StyleSheet.absoluteFill}
          />
          {this.renderMessage()}
        </View>
      </View>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM