Как сканировать один штрих-код за раз? [Реагируют родной-камеры] - PullRequest
0 голосов
/ 08 октября 2019

На самом деле я новичок в React и пытаюсь создать простой сканер штрих-кода, который показывает отсканированный штрих-код в предупреждении, и после нажатия «ОК» в предупреждении пользователь должен иметь возможность сканировать другой штрих-код.

Проблема заключается в том, что штрих-код непрерывно сканируется, и когда оповещение активируется, оно скрывается и каждую секунду отображает оповещение.

Я пытался сделать что-то подобное, чтобы показать оповещение только один раз, и еслиНажмите OK, чтобы иметь возможность снова показать предупреждение, но только в том случае, если нажата кнопка OK, но это не имело никакого эффекта.

  onBarCodeRead = (e) => {
    if(!this.alertPresent){
      this.alertPresent = true;
          Alert.alert(
            "Barcode type is " + e.type,
            "Barcode value is " + e.data,
            [
                 {text: 'OK', onPress: () => this.alertPresent = false;},
            ],
              {cancelable: false},
          );
      }
  }

Вот полный код Barcode.JS

import React, { Component } from 'react';
import { Button, Text, View,Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import BarcodeMask from 'react-native-barcode-mask';
class ProductScanRNCamera extends Component {

  constructor(props) {
    super(props);
    this.camera = null;
    this.barcodeCodes = [];
    this.alertPresent = false;
    this.state = {
      camera: {
        flashMode: RNCamera.Constants.FlashMode.auto,
      }
    };
  }

  onBarCodeRead = (e) => {
    if(!this.alertPresent){
      this.alertPresent = true;
          Alert.alert(
            "Barcode type is " + e.type,
            "Barcode value is " + e.data,
            [
                 {text: 'OK', onPress: () => this.alertPresent = false;},
            ],
              {cancelable: false},
          );
      }
  }


  pendingView() {
    return (
      <View
      style={{
        flex: 1,
        backgroundColor: 'lightgreen',
        justifyContent: 'center',
        alignItems: 'center',
      }}
      >
      <Text>Waiting</Text>
      </View>
    );
  }

  render() {


    return (
      <View style={styles.container}>
      <RNCamera
      ref={ref => {
        this.camera = ref;
      }}
      defaultTouchToFocus
      flashMode={this.state.camera.flashMode}
      mirrorImage={false}
      onBarCodeRead={this.onBarCodeRead.bind(this)}
      onFocusChanged={() => {}}
      onZoomChanged={() => {}}
      style={styles.preview}
      >
      <BarcodeMask/>
      </RNCamera>
      </View>
    );
  }
}

1 Ответ

0 голосов
/ 08 октября 2019

используйте setState для установки состояния component.setState возьмет объект и обновит состояние компонента

контрольный код ниже

import React, { Component } from 'react';
import { Button, Text, View, Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import BarcodeMask from 'react-native-barcode-mask';
class ProductScanRNCamera extends Component {

  constructor(props) {
    super(props);
    this.camera = null;
    this.barcodeCodes = [];
    this.showAlert = true;
    this.state = {
      camera: {
        flashMode: RNCamera.Constants.FlashMode.auto,
      }
    };
  }

  onBarCodeRead = (e) => {
    if (this.state.alertPresent) {
      this.setState({ showAlert: false });
      Alert.alert(
        "Barcode type is " + e.type,
        "Barcode value is " + e.data,
        [
          { text: 'OK', onPress: () =>console.log('ok')  },
        ],
        { cancelable: false },
      );
    }
  }


  pendingView() {
    return (
      <View
        style={{
          flex: 1,
          backgroundColor: 'lightgreen',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        <Text>Waiting</Text>
      </View>
    );
  }

  render() {

    return (
      <View style={styles.container}>
        <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          defaultTouchToFocus
          flashMode={this.state.camera.flashMode}
          mirrorImage={false}
          onBarCodeRead={this.onBarCodeRead.bind(this)}
          onFocusChanged={() => { }}
          onZoomChanged={() => { }}
          style={styles.preview}
        >
          <BarcodeMask />
        </RNCamera>
      </View>
    );
  }
}
...