一、安装插件
npm install jsbarcode --save
二、封装为一个单独的js文件,也可以不封装直接使用。
//封装为一个单独的文件 Barcode.js
import React, { Component } from 'react';
import JsBarcode from 'jsbarcode';
// 条形码
export default class Barcode extends Component {
static defaultProps = {
format: 'CODE128',
renderer: 'svg',
width: 1.6,
height: 25,
displayValue: true,
textAlign: 'center',
textPosition: 'bottom',
textMargin: 6,
fontSize: 14,
background: '#ffffff',
lineColor: '#000000',
margin: 0,
marginBottom: 0,
};
constructor(props) {
super(props);
this.update = this.update.bind(this);
};
componentDidMount() {
this.update();
};
componentDidUpdate() {
this.update();
};
handleBarcode = (r) => {
this.barcode = r;
}
update() {
const {
value,
format,
width,
height,
displayValue,
textAlign,
textPosition,
textMargin,
fontSize,
background,
margin,
lineColor,
marginBottom,
} = this.props;
JsBarcode(this.barcode, value, {
format,
width,
height,
displayValue,
textAlign,
textPosition,
textMargin,
fontSize,
background,
margin,
lineColor,
marginBottom,
})
};
render() {
const { renderer } = this.props;
if (renderer === 'svg') {
return (
<svg ref={this.handleBarcode} />
);
} else if (renderer === 'canvas') {
return (
<canvas ref={this.handleBarcode} />
);
} else if (renderer === 'img') {
return (
<img ref={this.handleBarcode} alt="" />
);
}
};
}
三、在react组件中使用
import Barcode from './Barcode.js';
//jsx内
<Barcode value={'102457899633'} height={50} width={2} />
//value为生成条形码的字符串,可由后端返回
PS:不封装为js,直接使用
import JsBarcode from 'jsbarcode';
import React,{useState,useEffect,useRef} from 'react';
const Barcode = () =>{
const [barcode,setBarcode] = useState(null); //设置生成条形码的初始串为空
const barcoderef = useRef()
useEffect(() =>{
initData()
},[])
useEffect(() =>{
//检测barcode有值了之后,可调用生成条形码方法
JsBarcode(barcoderef, barcode, {
displayValue: false,
width: 1.5,
height: 50,
margin: 0,
});
},[barcode])
const initData = () =>{
//可在此处调用接口请求,然后将接口返回的生成条形码的串赋值给barcode
setBarcode('10938388489494')
}
return (
<div className="barcode-box">
<svg
ref={barcoderef}
/>
</div>
);
}
如有问题 欢迎指教
转自:https://blog.csdn.net/Aym_zzz/article/details/106691253