You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何将二维码识别结果字符串存入变量?

Fixing Your QR Code Scanner Value Storage Issue

Hey there! Let's get your QR code scanner working properly and saving the scanned value to your qrcode variable. The core problems in your current code are missing state management for the scanned value, no permission handling for the camera, and no callback to capture the scan result from the BarCodeScanner component. Here's how to fix it step by step:

Step 1: Add State Management

Since you're using a class component, you'll need to initialize state to hold the scanned QR code value. Add this in your component's constructor:

constructor(props) {
  super(props);
  this.state = {
    qrcode: '',
    hasCameraPermission: null,
  };
}

Step 2: Request Camera Permission

Before using the scanner, you need to ask the user for camera access. Add these lifecycle methods to handle permission requests when the component mounts:

componentDidMount() {
  this.getCameraPermission();
}

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

Step 3: Add Scan Result Handler

Create a function that will update your state with the scanned QR code value when a scan is successful:

handleBarCodeScanned = ({ type, data }) => {
  this.setState({ qrcode: data });
  // Optional: Uncomment below to pause scanning after getting a result
  // this.scanner.current.stopScanning();
};

Step 4: Update the Render Method

Modify your render method to include the BarCodeScanner, handle permission states, and display the scanned value:

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

  if (hasCameraPermission === null) {
    return <Text>Requesting camera permission...</Text>;
  }
  if (hasCameraPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View style={styles.container}>
      <BarCodeScanner
        onBarCodeScanned={qrcode ? undefined : this.handleBarCodeScanned}
        style={StyleSheet.absoluteFillObject}
      />
      {qrcode && (
        <View style={styles.resultContainer}>
          <Text style={styles.resultText}>Scanned QR Code: {qrcode}</Text>
          <TouchableOpacity 
            style={styles.resetButton}
            onPress={() => this.setState({ qrcode: '' })}
          >
            <Text style={styles.resetButtonText}>Scan Again</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
}

Full Corrected Code

Here's the complete working code with all the fixes:

import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { Permissions, BarCodeScanner } from 'expo';

class HomeScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      qrcode: '',
      hasCameraPermission: null,
    };
  }

  componentDidMount() {
    this.getCameraPermission();
  }

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

  handleBarCodeScanned = ({ type, data }) => {
    this.setState({ qrcode: data });
  };

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

    if (hasCameraPermission === null) {
      return <Text>Requesting camera permission...</Text>;
    }
    if (hasCameraPermission === false) {
      return <Text>No access to camera</Text>;
    }

    return (
      <View style={styles.container}>
        <BarCodeScanner
          onBarCodeScanned={qrcode ? undefined : this.handleBarCodeScanned}
          style={StyleSheet.absoluteFillObject}
        />
        {qrcode && (
          <View style={styles.resultContainer}>
            <Text style={styles.resultText}>Scanned Value: {qrcode}</Text>
            <TouchableOpacity 
              style={styles.resetButton}
              onPress={() => this.setState({ qrcode: '' })}
            >
              <Text style={styles.resetButtonText}>Scan Another QR Code</Text>
            </TouchableOpacity>
          </View>
        )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  resultContainer: {
    position: 'absolute',
    bottom: 50,
    left: 20,
    right: 20,
    backgroundColor: 'rgba(255,255,255,0.9)',
    padding: 20,
    borderRadius: 10,
    alignItems: 'center',
  },
  resultText: {
    fontSize: 18,
    marginBottom: 15,
  },
  resetButton: {
    backgroundColor: '#2196F3',
    padding: 10,
    borderRadius: 5,
  },
  resetButtonText: {
    color: 'white',
    fontSize: 16,
  },
});

export default HomeScreen;

Key Changes Explained:

  • State Management: We added qrcode and hasCameraPermission to the component state to track the scanned value and camera access status.
  • Permission Handling: The getCameraPermission function ensures we have the necessary camera access before rendering the scanner.
  • Scan Callback: handleBarCodeScanned updates the state with the scanned data whenever a QR code is detected.
  • Conditional Rendering: We show different UI based on permission status, and display the scanned result once available (plus a button to reset and scan again).

Give this code a try, and your scanned QR code values should now be stored in the qrcode state variable correctly!

内容的提问来源于stack exchange,提问作者Brig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:59:54