首页指南参考教程

Expo BarCodeScanner iconExpo BarCodeScanner

允许扫描各种支持的条形码的库。它既可以作为独立库使用,也可以作为 Expo Camera 的扩展使用。


已弃用:从 SDK 51 起,该库将不再可用。我们建议使用内置条码扫描功能的 expo-camera

expo-barcode-scanner 提供了一个 React 组件,它为设备的相机(正面或背面)渲染取景器,并将扫描框架中显示的条形码。

¥expo-barcode-scanner provides a React component that renders a viewfinder for the device's camera (either front or back) and will scan bar codes that show up in the frame.

局限性

¥Limitations

当前仅支持一个活动的 BarCodeScanner 预览。

使用导航时,最佳实践是卸载任何先前渲染的 BarCodeScanner 组件,以便后续屏幕可以使用自己的 BarCodeScanner 而不会出现任何问题。

¥When using navigation, the best practice is to unmount any previously rendered BarCodeScanner component so the following screens can use their own BarCodeScanner without any issue.

已知的问题

¥Known issues

Android
iOS

BarCodeScanner 组件难以扫描黑色背景的条形码。这是底层 ZXing 库造成的限制。这也是 堆栈溢出线程 上讨论的一个问题。要解决此问题,你的应用应允许用户捕获条形码图片,然后在将图片传递到 BarCodeScanner 之前反转图片的颜色。

¥The BarCodeScanner component has difficulty scanning barcodes with black backgrounds. This is a limitation due to the underlying ZXing library. It is also an issue discussed on a Stack Overflow thread. To work around this, your app should allow users to capture the barcode image and then invert the colors of the image before passing it to the BarCodeScanner.

安装

¥Installation

Terminal
npx expo install expo-barcode-scanner

If you are installing this in an existing React Native app (bare workflow), start by installing expo in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.

app.json/app.config.js 中的配置

¥Configuration in app.json/app.config.js

如果你在项目中使用配置插件(EAS 构建npx expo run:[android|ios]),则可以使用其内置的 配置插件 配置 expo-barcode-scanner。该插件允许你配置无法在运行时设置的各种属性,并且需要构建新的应用二进制文件才能生效。

¥You can configure expo-barcode-scanner using its built-in config plugin if you use config plugins in your project (EAS Build or npx expo run:[android|ios]). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect.

Example app.json with config plugin

app.json
{
  "expo": {
    "plugins": [
      [
        "expo-barcode-scanner",
        {
          "cameraPermission": "Allow $(PRODUCT_NAME) to access camera."
        }
      ]
    ]
  }
}

Configurable properties

NameDefaultDescription
cameraPermission"Allow $(PRODUCT_NAME) to access your camera"
Only for:
iOS

A string to set the NSCameraUsageDescription permission message.

microphonePermission"Allow $(PRODUCT_NAME) to access your microphone"
Only for:
iOS

A string to set the NSMicrophoneUsageDescription permission message.

Are you using this library in a bare React Native app?

了解如何在 expo-barcode-scanner 存储库中的安装说明 文件中配置原生项目。

¥Learn how to configure the native projects in the installation instructions in the expo-barcode-scanner repository.

支持的格式

¥Supported formats

条形码格式安卓iOS 系统
aztec
codabar
code39*
code93
code128
code39mod43
datamatrix
ean13
ean8
interleaved2of5使用 itf14
itf14*
maxicode
pdf417*
rss14
rssexpanded
UPC_A
UPC_E
upc_ean
qr

补充注意

¥Additional notes

  1. 当识别 ITF-14 条码时,有时可以将其类型设置为 interleaved2of5

    ¥When an ITF-14 barcode is recognized, it's type can sometimes be set to interleaved2of5.

  2. 扫描 PDF417 和/或 Code39 格式可能会导致 iOS 上的电池消耗显着增加。建议仅提供你希望扫描到 barCodeTypes 属性的条形码格式。

    ¥Scanning for either PDF417 and/or Code39 formats can result in a noticeable increase in battery consumption on iOS. It is recommended to provide only the bar code formats you expect to scan to the barCodeTypes prop.

用法

¥Usage

在尝试获取用户的相机之前,你必须请求访问该相机的权限。为此,你需要使用 权限 API。你可以在下面的示例中实际看到这一点。

¥You must request permission to access the user's camera before attempting to get it. To do this, you will want to use the Permissions API. You can see this in practice in the following example.

Basic BarCodeScanner usage
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';

export default function App() {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);

  useEffect(() => {
    const getBarCodeScannerPermissions = async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    };

    getBarCodeScannerPermissions();
  }, []);

  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);
    alert(`Bar code with type ${type} and data ${data} has been scanned!`);
  };

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

  return (
    <View style={styles.container}>
      <BarCodeScanner
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={StyleSheet.absoluteFillObject}
      />
      {scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
  },
});

API

import { BarCodeScanner } from 'expo-barcode-scanner';

Component

Deprecated BarCodeScanner has been deprecated and will be removed in a future SDK version. Use expo-camera instead. See How to migrate from expo-barcode-scanner to expo-camera for more details.

BarCodeScanner

Type: React.Component<BarCodeScannerProps>

BarCodeScannerProps

barCodeTypes

Optional • Type: string[]

An array of bar code types. Usage: BarCodeScanner.Constants.BarCodeType.<codeType> where codeType is one of these listed above. Defaults to all supported bar code types. It is recommended to provide only the bar code formats you expect to scan to minimize battery usage.

For example: barCodeTypes={[BarCodeScanner.Constants.BarCodeType.qr]}.

onBarCodeScanned

Optional • Type: BarCodeScannedCallback

A callback that is invoked when a bar code has been successfully scanned. The callback is provided with an BarCodeScannerResult.

Note: Passing undefined to the onBarCodeScanned prop will result in no scanning. This can be used to effectively "pause" the scanner so that it doesn't continually scan even after data has been retrieved.

type

Optional • Type: 'front' | 'back' | number • Default: Type.back

Camera facing. Use one of BarCodeScanner.Constants.Type. Use either Type.front or Type.back. Same as Camera.Constants.Type.

Inherited Props

  • ViewProps

Hooks

usePermissions(options)

NameType
options
(optional)
PermissionHookOptions<object>

Check or request permissions for the barcode scanner. This uses both requestPermissionAsync and getPermissionsAsync to interact with the permissions.

Returns:

[null | PermissionResponse, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]

Example

const [permissionResponse, requestPermission] = BarCodeScanner.usePermissions();

Methods

BarCodeScanner.getPermissionsAsync()

Checks user's permissions for accessing the camera.

Returns:

Promise<PermissionResponse>

BarCodeScanner.requestPermissionsAsync()

Asks the user to grant permissions for accessing the camera.

On iOS this will require apps to specify the NSCameraUsageDescription entry in the Info.plist.

Returns:

Promise<PermissionResponse>

Return a promise that fulfills to an object of type PermissionResponse.

BarCodeScanner.scanFromURLAsync(url, barCodeTypes)

NameTypeDescription
urlstring

URL to get the image from.

barCodeTypes
(optional)
string[]

An array of bar code types. Defaults to all supported bar code types on the platform.

Note: Only QR codes are supported on iOS.


Scan bar codes from the image given by the URL.

Returns:

Promise<BarCodeScannerResult[]>

A possibly empty array of objects of the BarCodeScannerResult shape, where the type refers to the bar code type that was scanned and the data is the information encoded in the bar code.

Interfaces

PermissionResponse

An object obtained by permissions get and request functions.

PermissionResponse Properties

NameTypeDescription
canAskAgainboolean

Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission.

expiresPermissionExpiration

Determines time when the permission expires.

grantedboolean

A convenience boolean that indicates if the permission is granted.

statusPermissionStatus

Determines the status of the permission.


Types

BarCodeBounds

NameTypeDescription
originBarCodePoint

The origin point of the bounding box.

sizeBarCodeSize

The size of the bounding box.

BarCodeEvent

Type: BarCodeScannerResult extended by:


NameTypeDescription
target
(optional)
number-

BarCodeEventCallbackArguments

NameTypeDescription
nativeEventBarCodeEvent-

BarCodePoint

Those coordinates are represented in the coordinate space of the barcode source (e.g. when you are using the barcode scanner view, these values are adjusted to the dimensions of the view).

NameTypeDescription
xnumber

The x coordinate value.

ynumber

The y coordinate value.

BarCodeScannedCallback()

NameType
paramsBarCodeEvent

BarCodeScannerResult

NameTypeDescription
boundsBarCodeBounds

The BarCodeBounds object. bounds in some case will be representing an empty rectangle. Moreover, bounds doesn't have to bound the whole barcode. For some types, they will represent the area used by the scanner.

cornerPointsBarCodePoint[]

Corner points of the bounding box. cornerPoints is not always available and may be empty. On iOS, for code39 and pdf417 you don't get this value.

datastring

The parsed information encoded in the bar code.

typestring

The barcode type.

BarCodeSize

NameTypeDescription
heightnumber

The height value.

widthnumber

The width value.

PermissionHookOptions

Literal Type: multiple types

Acceptable values are: PermissionHookBehavior | Options

Enums

PermissionStatus

PermissionStatus Values

DENIED

PermissionStatus.DENIED = "denied"

User has denied the permission.

GRANTED

PermissionStatus.GRANTED = "granted"

User has granted the permission.

UNDETERMINED

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.

权限

¥Permissions

安卓

¥Android

通过该库的 AndroidManifest.xml 自动添加以下权限:

¥The following permissions are added automatically through this library's AndroidManifest.xml:

Android PermissionDescription

CAMERA

Required to be able to access the camera device.

iOS 系统

¥iOS

该库使用以下用法描述键:

¥The following usage description keys are used by this library:

Info.plist KeyDescription

NSCameraUsageDescription

A message that tells the user why the app is requesting access to the device’s camera.

NSMicrophoneUsageDescription

A message that tells the user why the app is requesting access to the device’s microphone.
Expo 中文网 - 粤ICP备13048890号