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

React中QRCode.toDataURL生成的二维码移动端不显示问题求助

移动端SVG中Base64二维码不显示的解决方案

针对桌面端正常、移动端SVG内Base64二维码完全不显示的问题,可从以下几个方向排查修复:

SVG 2已弃用xlink:href语法,部分移动端浏览器对旧语法支持度不足,直接改用标准href属性:

<image
    href={barCode}
    id="k"
    width={1024}
    height={1024}
/>

2. 避免生成无效的Base64数据

你的代码中默认值用了" "(空格),会导致QRCode生成无效的二维码数据,换成空字符串:

const fetchBarCode = () => {
    QRCode.toDataURL(certificate?.certificateURL ?? "", // 替换" "为""
        {
            color: {
                dark: '#7B4BA2',
                light: '#FFFFFF'
            },
            margin: 0
        })
        .then(url => {
            setBarCode(url);
        })
        .catch(err => {
            console.error(err)
        })
}

3. 确保SVG在数据加载完成后渲染

如果是React等框架环境,需添加条件渲染,避免在barCode为空时渲染<image>:

{barCode && (
    <image
        href={barCode}
        id="k"
        width="1024px"
        height="1024px"
    />
)}

(给尺寸添加px单位,部分移动端浏览器对无单位数值解析存在问题)

4. 尝试转成Blob URL替代Base64

部分移动端对SVG内的大体积Base64支持不佳,可将Base64转成Blob URL,兼容性更好:

const fetchBarCode = () => {
    QRCode.toDataURL(certificate?.certificateURL ?? "",
        {
            color: {
                dark: '#7B4BA2',
                light: '#FFFFFF'
            },
            margin: 0
        })
        .then(url => {
            // DataURL转Blob URL
            const arr = url.split(',');
            const mime = arr[0].match(/:(.*?);/)[1];
            const bstr = atob(arr[1]);
            const u8arr = new Uint8Array(bstr.length);
            for(let i = 0; i < bstr.length; i++) {
                u8arr[i] = bstr.charCodeAt(i);
            }
            const blobUrl = URL.createObjectURL(new Blob([u8arr], {type: mime}));
            setBarCode(blobUrl);
        })
        .catch(err => {
            console.error(err)
        })
}

(注意组件卸载时调用URL.revokeObjectURL(barCode)释放资源)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:15:17