一、引入依赖(我的版本^2.3.8)
npm i html5-qrcode
二、编写扫码组件
import React, {useEffect, useState} from "react";
import {Html5Qrcode} from "html5-qrcode";
import {Toast} from "antd-mobile";
import {useNavigate} from "react-router-dom";
const BarcodeScanner = () => {
const navigate = useNavigate();
const [barCode,setBarCode] = useState(null)
useEffect(() => {
//如果状态有值,返回上一页面,防止触发重复扫描的bug
if (barCode){
sessionStorage.setItem("barCode",JSON.stringify(barCode))
navigate(-1)
return
}
sessionStorage.removeItem("barCode")//每次进入扫码组件清空一次临时缓存
const html5QrCode = new Html5Qrcode('reader');//渲染容器
const timer2 = setInterval(()=>{
html5QrCode.start(
// { facingMode: "user" }, //前置摄像头
{
facingMode: "environment" //后置摄像头
},
{
fps: 10,
qrbox: 250,
torch: true // 设置允许开启手机手电筒,貌似没用
},
qrCodeMessage => {
if (qrCodeMessage) {
//扫描成功,记录到临时缓存中。因为设置状态会有状态更新问题,导致返回上一级页面无数据
setBarCode(barCode)//扫描成功,设置状态值
Toast.show({content: "扫描成功!"})
sessionStorage.setItem("barCode",JSON.stringify(qrCodeMessage))
navigate(-1)//返回上一页面,从哪里来,回哪里去
}
},
errorMessage => {
//错误->提示
Toast.show({content: "提示:请对准二维码/条形码!", position: "bottom"})
}
);
},500)
return () => {
html5QrCode.stop();//停止扫描
clearInterval(timer2)
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <div id="reader"></div>;//创建一个容器
};
export default BarcodeScanner;