首页 > 解决方案 > 无法使用 useRef 挂钩访问 toDataUrl()?

问题描述

我正在我的功能组件中生成一个二维码。我想将二维码复制到剪贴板或下载二维码。我将 Ref 传递给 QRCode 组件。但我不能在我的监听器中使用 ref.current.toDataUrl() 。

React 包 - react-qrcode-logo

我尝试了两种不同的方法。

  1. 下载QR() -> 不起作用。我想这不应该起作用,因为我使用了反应钩子。

2.downloadQR2() -> 它说 toDataURL() 没有为 ref 定义。

console.log(containerRef.current) 在控制台上打印了这个。
在此处输入图像描述

    const downloadQR2 = () => {
        const canvas = containerRef.current;
        console.log(canvas.toDataURL());
    }

    const downloadQR = () => {
        const canvas = document.getElementById("canvas-id");
        const pngUrl = canvas
          .toDataURL("image/png")
          .replace("image/png", "image/octet-stream");
        let downloadLink = document.createElement("a");
        downloadLink.href = pngUrl;
        downloadLink.download = "QRcode.png";
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      };

//Componenet
   <QRCode id="canvas-id" ref={containerRef} value={url} logoImage={stackedLogo}/>

我是 React 的新手。我不知道如何处理任务?任何人都可以分享一些见解或指出我正确的方向吗?

标签: reactjsqr-codehtml2canvas

解决方案


问题containerRef.currentQRCode组件。它不是canvas。从日志中可以看出,canvascontainerRef.current.canvas.current.


推荐阅读