小工具知识网

当前位置: 首页 > 行业知识 > React实现生成及打印二维码

行业知识

React实现生成及打印二维码

2026-11-29 04:30:17 来源:互联网转载

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

使用到的两个组件:

1、生成二维码

yarn add qrcode

2、打印

yarn add react-print-html

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

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();  const [routingList, setRoutingList] = useState([]);  const [tableLoading, setTableLoading] = useState(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 (          { display: 'inline-block' }}        onClick={() => {          setIsModalOpen(true);          // getList();        }}      >        {children}             {          setIsModalOpen(false);          formRef.current?.resetFields();        }}        footer={null}      >                              { marginLeft: 20 }} disabled={!routingList.length}              {intl.formatMessage({                id: 'component.option.print',                defaultMessage: '打印',              })}                                                {routingList.map((item) => {            return (              { marginTop: 30}}>                {display: 'inline-block', verticalAlign: 'middle'}}>                  {width:"100px",height:"100px"}}                                {display: 'inline-block', verticalAlign: 'middle'}}>                                      {intl.formatMessage({                      id: 'component.option.productionOrder.table.lotNo',                      defaultMessage: '号码一',                    })}: {item.lotNo}                                      {intl.formatMessage({                      id: 'component.option.part.table.drawingNo',                      defaultMessage: '号码二',                    })}: {item.drawingNo}                                      {intl.formatMessage({                      id: 'component.option.workOrder.table.productionOrderNo',                      defaultMessage: '号码三',                    })}: {item.productionOrderNo}                                          )          })}                    );};

补充说明几点:

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

实现效果:

上一篇:轻松下载抖音伙伴教程,一步步带你搞定!

下一篇:云空间云服务器价格