You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Modal内html5-qrcode相机预览加载延迟问题求助

Modal内html5-qrcode相机预览加载延迟问题求助

大家好,我最近在开发扫码功能时遇到了个体验问题:当Modal弹窗打开后,html5-qrcode的相机预览总要等1-2秒才会显示出来,没法和弹窗做到同步加载,想请教下各位有没有解决思路?

先贴下我的核心代码实现:

useEffect(() => {
  if (isOpen && !isSaved) {
    let html5QrCode: Html5Qrcode | null = null;
    const startScanner = async () => {
      try {
        html5QrCode = new Html5Qrcode("barcode-scanner");
        scannerRef.current = html5QrCode as Html5Qrcode;
        if (html5QrCode) {
          try {
            const devices = await Html5Qrcode.getCameras();
            if (devices && devices.length > 0) {
              const cameraId: any = devices[devices.length - 1]; // 优先用后置摄像头
              await html5QrCode.start(
                cameraId.id,
                { fps: 10 },
                (decodedText: string) => {
                  handleBarCodeScanned({ data: decodedText });
                },
                () => {} // 忽略扫码错误
              );
            }
          } catch (fallbackError) {
            console.error("所有相机尝试均失败:", fallbackError);
          }
        }
        console.log("扫码器启动成功");
      } catch (error: any) {
        console.error("扫码器启动失败:", error);
      }
    };
    startScanner();

    // 清理函数
    return () => {
      if (html5QrCode) {
        html5QrCode.stop()
          .then(() => {
            html5QrCode?.clear();
            console.log("扫码器已停止并清理");
          })
          .catch((error: any) => {
            console.error("停止扫码器出错:", error);
          });
      }
    };
  }
}, [isOpen, isSaved, handleBarCodeScanned]);

return (
  <>
    <InputFormElement
      {...props}
      placeholder={
        !hasPermission ? '无相机权限,请检查设备设置' : ''
      }
      defaultValue={newBarcode}
      InputRightElement={
        <IconBarCode
          onPress={handleScan}
          mr={1}
          ml={1}
          disabled={isInputReadOnly}
        />
      }
      onChangeText={handleChange}
      rules={validationRules}
    />
    <Modal
      isOpen={isOpen && !isSaved}
      onClose={handleModalClose}
      _overlay={{ useRNModal: true }}
      size={'xl'}
    >
      <Modal.Content>
        <Modal.CloseButton />
        <Modal.Header>Scan a bar code</Modal.Header>
        <div id="barcode-scanner" style={{ width: '100%' }} />
      </Modal.Content>
    </Modal>
  </>
);

我目前的处理逻辑是:用useEffect监听isOpen状态,当弹窗打开且未保存时启动扫码器,指定获取最后一个相机(一般是后置摄像头),组件卸载时也做了stop+clear的清理操作防止内存泄漏,但还是没法解决相机预览延迟的问题。

有没有大佬能帮忙分析下问题出在哪,或者有什么优化方案能让相机预览和Modal弹窗同步显示?

内容来源于stack exchange

火山引擎 最新活动