qrcode

      • 1 安装
      • 2 引入
      • 3 使用
        • 3.1 方法1 :QRCode.toCanvas()
        • 3.2 方法2 :QRCode.toDataURL()
      • 4 完整示例

qrcode 是一个用于生成二维码的 JavaScript 库。主要是通过获取 DOM 的标签,再通过 HTML5 Canvas 绘制而成

1 安装

npm install --save qrcode

2 引入

import QRCode from 'qrcode';

如果您使用的 TypeScript,则在引入的时候可能会提示一下 error:

使用 qrcode 生成二维码

无法找到模块“qrcode”的声明文件。“C:/Users/shaoming/Desktop/swimxu/swim-react/node_modules/qrcode/lib/index.js”隐式拥有 “any” 类型。

尝试使用 npm i --save-dev @types/qrcode (如果存在),或者添加一个包含 declare module 'qrcode'; 的新声明(.d.ts)文件ts(7016)

则需要安装 @types/qrcode,即可解决。

npm install --save @types/qrcode

3 使用

3.1 方法1 :QRCode.toCanvas()

直接操作DOM,适合用于将二维码直接下载到本地。

<canvas id='canvas' />
const canvas = document.getElementById('canvas'); // 获取canvas节点
QRCode.toCanvas(canvas, '二维码中存储的数据内容'); // 绘制二维码

3.2 方法2 :QRCode.toDataURL()

适合 react 使用。

<img src={imgUrl} />
const [imgUrl, setImgUrl] = useState('')
......
QRCode.toDataURL('二维码中存储的数据内容', (error: Error | null | undefined, url: string) => {
	setImgUrl(url); // 将获取的url存到state中,方便img标签中使用
});

4 完整示例

React 使用 qrcode 实例:

import { useState } from 'react';
import { Button } from 'antd';
import QRCode from 'qrcode';
const View = () => {
  const [imgUrl, setImgUrl] = useState('')
  const handleClick = async () => {
    const value = '二维码中存储的数据内容'
	const canvas = document.getElementById('canvas');
    QRCode.toCanvas(canvas, value);
    QRCode.toDataURL(value, (error: Error | null | undefined, url: string) => {
      setImgUrl(url);
    });
  }
  return (
    <div style={{ width: 240, margin: '100px auto', textAlign: 'center' }}>
      <Button
        type='primary'
        onClick={handleClick}
        style={{ width: 240, margin: '40px auto' }}
      >
        点击生成二维码
      </Button>
      <canvas id='canvas' />
      <img src={imgUrl} />
    </div >
  )
}
export default View
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。