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参数是二维码的内容

实现效果:

相关推荐
清幽竹客5 分钟前
vue-37(模拟依赖项进行隔离测试)
前端·vue.js
vvilkim5 分钟前
Nuxt.js 页面与布局系统深度解析:构建高效 Vue 应用的关键
前端·javascript·vue.js
滿9 分钟前
Vue3 父子组件表单滚动到校验错误的位置实现方法
前端·javascript·vue.js
专注VB编程开发20年9 分钟前
javascript的类,ES6模块写法在VSCODE中智能提示
开发语言·javascript·vscode
夏梦春蝉1 小时前
ES6从入门到精通:模块化
前端·ecmascript·es6
拓端研究室2 小时前
视频讲解:门槛效应模型Threshold Effect分析数字金融指数与消费结构数据
前端·算法
工一木子3 小时前
URL时间戳参数深度解析:缓存破坏与前端优化的前世今生
前端·缓存
半点寒12W5 小时前
微信小程序实现路由拦截的方法
前端
某公司摸鱼前端6 小时前
uniapp socket 封装 (可拿去直接用)
前端·javascript·websocket·uni-app
要加油哦~6 小时前
vue | 插件 | 移动文件的插件 —— move-file-cli 插件 的安装与使用
前端·javascript·vue.js