You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中React使用useRef绑定div实现二维码下载报类型错误如何解决

报错原因

你在初始化useRef时没有指定泛型类型,也未设置初始值,TypeScript会自动推断该ref的current属性类型为undefined,但绑定到div元素的ref要求current属性类型为HTMLDivElement | null,二者类型不匹配导致TS报错。

解决方法

  1. 给useRef添加泛型声明并指定初始值为null,替换原来的ref声明代码:
const qrRef = React.useRef<HTMLDivElement>(null);
  1. 优化downloadQRCode方法里的取值逻辑,添加空值判断和类型断言,移除@ts-ignore注解:
const downloadQRCode = (evt: React.FormEvent) =>{
    evt.preventDefault();
    // 用可选链规避空值报错,同时断言canvas类型
    const canvas = qrRef.current?.querySelector("canvas") as HTMLCanvasElement | null;
    if (!canvas) return; // 没有获取到canvas时直接终止逻辑
    const image = canvas.toDataURL("image/png");
    const anchor = document.createElement("a");
    anchor.href = image;
    anchor.download="qr-code.png";
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
    
    setUrl("");
};

修改完成后类型报错会直接消失,同时也规避了运行时可能出现的空值异常问题。

内容的提问来源于stack exchange,提问作者Miko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:06:05