1. 安装qrcode.react插件

  1. yarn add qrcode.react
  2. // or
  3. npm install qrcode.react --save

2. 使用qrcode.react插件生成二维码

  • 引入

    1. import QRCode from 'qrcode.react';
  • 使用

    1. <QRCode
    2. id="qrCode"
    3. value="https://www.jianshu.com/u/992656e8a8a6"
    4. size={200} // 二维码的大小
    5. fgColor="#000000" // 二维码的颜色
    6. style={{ margin: 'auto' }}
    7. imageSettings={{ // 二维码中间的logo图片
    8. src: 'logoUrl',
    9. height: 100,
    10. width: 100,
    11. excavate: true, // 中间图片所在的位置是否镂空
    12. }}
    13. />

    下载

    1. <Button type="link" onClick={this.ClickDownLoad}>
    2. 下载二维码
    3. </Button>
    1. ClickDownLoad = (codeid, e) => {
    2. const canvasImg = document.getElementById('qrcode');
    3. console.log(canvasImg, 'canvasImg');
    4. console.log(canvasImg.toDataURL('image/png'), 'canvasImg.toDataURL');
    5. // const canvasImg = document.getElementById('qrCode'); // 获取canvas类型的二维码
    6. // const img = new Image();
    7. const url = canvasImg.toDataURL('image/png'); // 将canvas对象转换为图片的data url
    8. this.downloadFile('测试.png', url);
    9. };
    10. //下载
    11. downloadFile = (fileName, content) => {
    12. let aLink = document.createElement('a');
    13. let blob = this.base64ToBlob(content); //new Blob([content]);
    14. let evt = document.createEvent('HTMLEvents');
    15. evt.initEvent('click', true, true); //initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
    16. aLink.download = fileName;
    17. aLink.href = URL.createObjectURL(blob);
    18. // aLink.dispatchEvent(evt);
    19. //aLink.click()
    20. aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window})); //兼容火狐
    21. };
    22. //base64转blob
    23. base64ToBlob = code => {
    24. let parts = code.split(';base64,');
    25. let contentType = parts[0].split(':')[1];
    26. let raw = window.atob(parts[1]);
    27. let rawLength = raw.length;
    28. let uInt8Array = new Uint8Array(rawLength);
    29. for (let i = 0; i < rawLength; ++i) {
    30. uInt8Array[i] = raw.charCodeAt(i);
    31. }
    32. return new Blob([uInt8Array], {type: contentType});
    33. };