reactjs - 无法使用 useRef 挂钩访问 toDataUrl()?
问题描述
我正在我的功能组件中生成一个二维码。我想将二维码复制到剪贴板或下载二维码。我将 Ref 传递给 QRCode 组件。但我不能在我的监听器中使用 ref.current.toDataUrl() 。
React 包 - react-qrcode-logo
我尝试了两种不同的方法。
- 下载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 的新手。我不知道如何处理任务?任何人都可以分享一些见解或指出我正确的方向吗?
解决方案
问题containerRef.current
是QRCode
组件。它不是canvas
。从日志中可以看出,canvas
是containerRef.current.canvas.current
.
推荐阅读
- javascript - JS Canvas 运动动画循环
- lua - 我有一个 gLua 错误:错误的参数 #1 到 'lower'(需要字符串,得到 nil)
- wpf - WPF MVVM 在视图模型之间传递数据但属性未更新
- flutter - Flutter 动画变得非常滞后
- javascript - 如何隐藏没有值的行
- java - Android Studio 拒绝运行 main()
- mysql - SQL JOIN 作为单行,子值作为列,并且能够 ORDER BY 子关系值
- jquery - HTML按钮元素没有输出任何东西
- javascript - 使用 Javascript 缩短重复/多个属性
- reactjs - FlatList 仅在 react native 中显示一个 REST API 的数据