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. react18+ts如何生成并且下载

    2024-05-14 14:58:04       38 阅读
  2. vue中qrcanvas生成并且下载

    2024-05-14 14:58:04       62 阅读
  3. 【taro react】 ---- QRCode 生成

    2024-05-14 14:58:04       64 阅读
  4. 生成

    2024-05-14 14:58:04       64 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-14 14:58:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-14 14:58:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-14 14:58:04       87 阅读
  4. Python语言-面向对象

    2024-05-14 14:58:04       96 阅读

热门阅读

  1. Kibana初始化启动失败原因及解决办法

    2024-05-14 14:58:04       38 阅读
  2. Day38 斐波那契数 + 爬楼梯 + 使用最小花费爬楼梯

    2024-05-14 14:58:04       32 阅读
  3. 瑞鹤仙——熊市出英雄

    2024-05-14 14:58:04       27 阅读
  4. mysql 拆分字段位多行

    2024-05-14 14:58:04       23 阅读
  5. Docker alpine linux 修改时区

    2024-05-14 14:58:04       37 阅读
  6. 树和二叉树_1

    2024-05-14 14:58:04       29 阅读