React实现生成及打印二维码

前言:react中一般生成二维码都是用react.qrcode,但是发现这玩意生成的是canvas,不是图片,打印的时候预览不出来。所以想进一切办法去把canvas转成图片,无奈拿不到这个canvas标签。最后还是用js的qrcode来生成二维码,这样生成的默认是base64位的图片,打印正常。

使用到的两个组件:

1、生成二维码

javascript 复制代码
yarn add qrcode

2、打印

javascript 复制代码
yarn add react-print-html

参考代码(部分代码,不可直接粘贴运行)

javascript 复制代码
import { Button, Modal, Table, TableProps } from 'antd';
import { useRef, useState } from 'react';
import Print from 'react-print-html'
let QRCode = require('qrcode')

export default (props: PropsType) => {
  const { children } = props;
  const intl = useIntl();
  let printTemp = useRef(null)
  const formRef = useRef<ProFormInstance>();
  const [routingList, setRoutingList] = useState<TableDataType[]>([]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const [qrcodeImg, setQrcodeImg] = useState(undefined)

  const getCode =(lotNo: string) =>{
    QRCode.toDataURL(lotNo)
    .then((url: any) => {
      setQrcodeImg(url)
    })
    .catch((err: any) => {
        console.error(err)
    })
  }

  const getList = async () => {
    const res: any = await request({});
    if (res.data?.lot?.length) {
      setRoutingList(res.data.lot);
      getCode(res.data.lot[0].lotNo)
    } else {
      setRoutingList([])
    }
    setTableLoading(false);
  };

  const handlePrint = () => {
    setTimeout(() => {
      Print(printTemp.current)
    })
  };

  return (
    <>
      <div
        style={{ display: 'inline-block' }}
        onClick={() => {
          setIsModalOpen(true);
          // getList();
        }}
      >
        {children}
      </div>
      <Modal
        open={isModalOpen}
        title={children}
        width="60%"
        onCancel={() => {
          setIsModalOpen(false);
          formRef.current?.resetFields();
        }}
        footer={null}
      >
        <ProForm>
          <ProFormItem>
            <Button type="primary" danger onClick={handlePrint} style={{ marginLeft: 20 }} disabled={!routingList.length}>
              {intl.formatMessage({
                id: 'component.option.print',
                defaultMessage: '打印',
              })}
            </Button>
          </ProFormItem>
        </ProForm>
        <div ref={printTemp}>
          {routingList.map((item) => {
            return (
              <div key={item.id} style={{ marginTop: 30}}>
                <div style={{display: 'inline-block', verticalAlign: 'middle'}}>
                  <img src={qrcodeImg} style={{width:"100px",height:"100px"}}></img>
                </div>
                <div style={{display: 'inline-block', verticalAlign: 'middle'}}>
                  <div>
                    {intl.formatMessage({
                      id: 'component.option.productionOrder.table.lotNo',
                      defaultMessage: '号码一',
                    })}: {item.lotNo}</div>
                  <div>
                    {intl.formatMessage({
                      id: 'component.option.part.table.drawingNo',
                      defaultMessage: '号码二',
                    })}: {item.drawingNo}</div>
                  <div>
                    {intl.formatMessage({
                      id: 'component.option.workOrder.table.productionOrderNo',
                      defaultMessage: '号码三',
                    })}: {item.productionOrderNo}</div>
                </div>
              </div>
            )
          })}
        </div>
      </Modal>
    </>
  );
};

补充说明几点:

  1. QRCode.toDataURL(lotNo) 其中的lotNo参数是二维码的内容

实现效果:

相关推荐
叉歪1 天前
实现在 UnoCSS 中使用任意深度颜色的预设
前端·css
一 乐1 天前
二手车销售|汽车销售|基于SprinBoot+vue的二手车交易系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·汽车
Giant1001 天前
如果要做优化,CSS提高性能的方法有哪些?
前端
dllxhcjla1 天前
html初学
前端·javascript·html
只会写Bug的程序员1 天前
【职业方向】2026小目标,从web开发转型web3开发【一】
前端·web3
LBuffer1 天前
破解入门学习笔记题二十五
服务器·前端·microsoft
kuxku1 天前
使用 SSE 与 Streamdown 实现 Markdown 流式渲染
前端·javascript·node.js
Sherry0071 天前
【译】🔥如何居中一个 Div?看这篇就够了
前端·css·面试
前端小咸鱼一条1 天前
18. React的受控和非受控组件
前端·react.js·前端框架
一枚前端小能手1 天前
🛠️ Service Worker API深度解析 - 生命周期、缓存与离线实战
前端·javascript