无法使用useRef钩子访问toDataUrl()?

时间:2019-08-04 06:04:25

标签: reactjs qr-code html2canvas

我正在功能组件中生成QRCode。我想将QRcode复制到clipbaord或下载QRcode。我将Ref传递到QRCode组件中。但是我不能在侦听器中使用ref.current.toDataUrl()。

反应包-react-qrcode-logo

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

  1. downloadQR()->不起作用。我想这不起作用,因为我使用了React钩子。

2.downloadQR2()->它表示未为引用定义toDataURL()。

console.log(containerRef.current)将其打印在控制台上。
enter image description here

    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中还很新。 我对如何处理任务迷失了?任何人都可以分享一些见识或为我指出正确的方向吗?

1 个答案:

答案 0 :(得分:1)

问题是<%= form_for @your_data , :html => {:autocomplete=> 'off'} do |f| %> containerRef.current组件。不是QRCode。从日志中可以看到,canvascanvas