这里提供两种方法:
第一种:使用qrcode.react插件
这是最简单的一种用法,
npm install qrcode.react --save
import QRCode from 'qrcode.react';
<QRCode
value={this.state.qrUrl} //value参数为生成二维码的链接
size={200} //二维码的宽高尺寸
fgColor="#000000" //二维码的颜色
/>
后来,我发现这个插件也可以直接单独拿出它的index文件,放到自己代码里面,姜将这个index文件当作一个组件调用,使用法不变,
这个index文件可以直接在我的网盘里面下载
链接: https://pan.baidu.com/s/1bI2MiQoyyR25CaetJsfl0Q
密码: d15g
第二种:用原生js实现二维码功能
1、在项目下引入js基础代码 qrcode.js
将图片放到public文件里面,再在index.html里面引入,当然,大家可以按照自己的需求将它放到想要的位置,qrcode.js文件我放到百度网盘上了,想要的可以自己下载一下,
链接: https://pan.baidu.com/s/1AqvnQQ6v90xhi_UsdlahHA
密码: 6ljc
2、使用
主要代码
createdCode() {
var qrcode = new window.QRCode(document.getElementById("qrcode"), {
text: 'url or text', // 这里是二维码的内容
width: 150,
height: 150
});
// qrcode.makeCode('123456') // 也可以用这个方法修改上面的title内容
}
<div id={"qrcode"} />
注意:
这个方法有个坑,就是如果一个页面上显示多个二维码的时候会出现多个二维码挤到一起的现象
解决方法就是<div id={“qrcode”} />里面的id不能固定,也就相当于key值不能重复一个道理
完整代码如下:
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
export class Qrcode extends Component {
constructor(props){
super(props);
this.state = {}
}
componentDidMount(){
this.createdCode()
}
createdCode() {
const {value} = this.props
var qrcode = new window.QRCode(document.getElementById(value), {
text: '这里是二维码的内容', // url or text
width: 150,
height: 150
});
// qrcode.makeCode('123456')
}
render() {
const {value} = this.props
return (
<div style={{backgroundColor:'#fff',padding:'10px',display:'inline-block'}}>
<div id={value} />
</div>
);
}
}
export default withRouter(Qrcode);