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

React中使用BarcodeScannerComponent获取扫描结果后如何停止扫描

问题根因

react-webcam-barcode-scanner 组件默认会持续调用摄像头运行扫描逻辑,你当前定义的scann状态仅做了本地存储,没有和组件的启停逻辑关联,仅修改状态不会触发扫描停止,单纯移除组件焦点也无法终止底层的摄像头视频流捕获。

修复方案

提供两种常用实现方式,可根据业务场景选择:

方案1:条件渲染卸载组件(扫完即关闭扫描画面)

扫到有效结果后直接卸载扫描组件,自动释放摄像头资源,完全终止扫描进程:

import React, { Component } from "react";
import BarcodeScannerComponent from "react-webcam-barcode-scanner";

export default class GetCodeEditor extends Component<any, any> {
 constructor(props: any) {
   super(props);
   this.state = {
     value: this.props.value || "",
     scanning: this.props.scann || true, // 调整命名更贴合语义,true表示正在扫描
     data: []
   }
 }
 getValue() {
   if (this.props.value === null && this.state.value === "") {
     return null;
   }
   return this.state.value;
 }

 isPopup() {
   return !this.state.scanning;
 }

 render() {
   // 仅在scanning为true时渲染扫描组件,否则渲染结果
   return this.state.scanning ? (
       <BarcodeScannerComponent
         width={500}
         height={500}
         onUpdate={(err, result: any) => {
           if (result) {
             this.setState({
               scanning: false, // 扫到结果后关闭扫描状态
               value: result.text,
             });
             this.isPopup();
             console.log("Test:" + this.state.scanning + " "  + result.text);
           }
           else if(err) {
             this.setState({
               scanning: false,
               value: 'Not Found',
             });
           }
         }}
       />
   ) : <div>扫描结果:{this.state.value}</div>
  }
}

方案2:使用pause属性暂停扫描(保留扫描画面)

如果业务需要保留扫描画面仅停止识别,可以用组件原生支持的pause属性控制:

// 仅展示修改部分代码
render() {
   return (
       <BarcodeScannerComponent
         width={500}
         height={500}
         pause={!this.state.scanning} // 扫描状态为false时暂停识别
         onUpdate={(err, result: any) => {
           if (result) {
             this.setState({
               scanning: false,
               value: result.text,
             });
             console.log("Test:" + this.state.scanning + " "  + result.text);
           }
         }}
       />
   );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 18:45:03