无法使用 useRef 挂钩访问 toDataUrl()?
Can't access toDataUrl() using the useRef hook?
我正在我的功能组件中生成二维码。我想将二维码复制到剪贴板或下载二维码。我将 Ref 传递到 QRCode 组件中。但是我不能在我的监听器中使用 ref.current.toDataUrl() 。
React 包 - react-qrcode-logo
我尝试了两种不同的方法。
- downloadQR() -> 不起作用。我想这不应该起作用,因为我正在使用反应钩子。
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 的新手。
我迷失了如何处理任务?谁能分享一些见解或为我指明正确的方向?
问题是 containerRef.current
是 QRCode
组件。它不是canvas
。从日志中可以看出,canvas
是containerRef.current.canvas.current
。
我正在我的功能组件中生成二维码。我想将二维码复制到剪贴板或下载二维码。我将 Ref 传递到 QRCode 组件中。但是我不能在我的监听器中使用 ref.current.toDataUrl() 。
React 包 - react-qrcode-logo
我尝试了两种不同的方法。
- downloadQR() -> 不起作用。我想这不应该起作用,因为我正在使用反应钩子。
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 的新手。 我迷失了如何处理任务?谁能分享一些见解或为我指明正确的方向?
问题是 containerRef.current
是 QRCode
组件。它不是canvas
。从日志中可以看出,canvas
是containerRef.current.canvas.current
。