react18+ts如何生成二维码并且下载

目录

一、下载qrcode.react

二、引入qrcode.react

三 、编写下载二维码的函数


在react开发中如果需要二维码,笔者选择使用qrcode.react来快速生成。

一、下载qrcode.react

pnpm add qrcode.react

二、引入qrcode.react

import {Box,Stack,Fab} from '@mui/material';
import { QRCodeCanvas } from 'qrcode.react';
import { useState} from "react";
export const Component = () => {
 const currentUrl = window.location.protocol + '//' + window.location.host;
 console.log('🚀 ~ file: Receive.tsx:33 ~ Component ~ currentUrl:', currentUrl);
  const [qrValue, setQrValue] = useState(currentUrl);
  return (
    <Box>
      <Stack direction="row" justifyContent="center" alignItems="center" mb={3}>
        <Box>
          <QRCodeCanvas
            id="qrCode"
            value={qrValue}
            size={128}
            imageSettings={{
              excavate: true,
              src: '/logo-128.png',
              width: 30,
              height: 30
            }}
          />
        </Box>
      </Stack>
    </Box>
  );
};

Component.displayName = 'ReceivePage';

 qrcode.react具体配置参数请参考官网qrcode.react

三 、编写下载二维码的函数

 //base64转文件
  const dataURLtoBlob = (dataurl: string) => {
    const arr = dataurl.split(',') as any;
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  };
  //创建a标签用于下载
  const downloadFile = (url: string, name: string) => {
    const a = document.createElement('a');
    a.setAttribute('href', url);
    a.setAttribute('download', name);
    a.setAttribute('target', '_blank');
    a.dispatchEvent(new MouseEvent('click'));  //模拟点击
    /*    const clickEvent = document.createEvent('MouseEvents');
    clickEvent.initEvent('click', true, true); //模拟点击,initEvent(方法已经弃用)
    a.dispatchEvent(clickEvent); */
  };
//下载二维码
 const handleDownLoadQRCode = () => {
     //先获取要下载的二维码
     const Qr = document.getElementById('qrCode') as any;
     //把canvas的数据改成base64的格式
      const canvasUrl = Qr!.toDataURL('image/png');
      const myBlob = dataURLtoBlob(canvasUrl);
      const myUrl = URL.createObjectURL(myBlob); // 创建blob下载地址
      downloadFile(myUrl, 'qrCode');
    
  };

最后附上完整代码:

import { Box, Stack, Fab } from '@mui/material';
import { QRCodeCanvas } from 'qrcode.react';
import { useState } from 'react';
export const Component = () => {
  const currentUrl = window.location.protocol + '//' + window.location.host;
  console.log('🚀 ~ file: Receive.tsx:33 ~ Component ~ currentUrl:', currentUrl);
  const [qrValue, setQrValue] = useState(currentUrl);
  //base64转文件
  const dataURLtoBlob = (dataurl: string) => {
    const arr = dataurl.split(',') as any;
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  };
  //创建a标签用于下载
  const downloadFile = (url: string, name: string) => {
    const a = document.createElement('a');
    a.setAttribute('href', url);
    a.setAttribute('download', name);
    a.setAttribute('target', '_blank');
    a.dispatchEvent(new MouseEvent('click')); //模拟点击
    /*    const clickEvent = document.createEvent('MouseEvents');
    clickEvent.initEvent('click', true, true); //模拟点击,initEvent(方法已经弃用)
    a.dispatchEvent(clickEvent); */
  };
  //下载二维码
  const handleDownLoadQRCode = () => {
    //先获取要下载的二维码
    const Qr = document.getElementById('qrCode') as any;
    //把canvas的数据改成base64的格式
    const canvasUrl = Qr!.toDataURL('image/png');
    const myBlob = dataURLtoBlob(canvasUrl);
    const myUrl = URL.createObjectURL(myBlob); // 创建blob下载地址
    downloadFile(myUrl, 'qrCode');
  };

  return (
    <Box>
      <Stack direction="row" justifyContent="center" alignItems="center" mb={3}>
        <Box>
          <QRCodeCanvas
            id="qrCode"
            value={qrValue}
            size={128}
            imageSettings={{
              excavate: true,
              src: '/logo-128.png',
              width: 30,
              height: 30
            }}
          />
        </Box>
      </Stack>
      <Stack direction="row" justifyContent="space-around">
        <Fab color="primary" variant="extended" size="small" onClick={handleDownLoadQRCode}>
          点击下载二维码
        </Fab>
      </Stack>
    </Box>
  );
};

Component.displayName = 'ReceivePage';

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任磊abc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值