npm install jsbarcode --save
只做简单记录,详细使用方法查看README.md文档
方法1:这种方法适合直接操作DOM
// 条码
const canvas = document.createElement('canvas');
Barcode(canvas, value, {
format: 'CODE128', // 条形码类型
displayValue: false, // 否在条形码下方显示文字
});
Handsontable.dom.empty(TD);
TD.appendChild(canvas);
方法2:这种方法适合react使用
首先写一个react类组件cs-barcode.tsx
import React from 'react';
import JsBarcode from 'jsbarcode';
interface CSBarcodeProps {
value: string; // 要编入的文本
renderer: string; // 渲染类型:svg|canvas|img
options: JsBarcode.Options; // 配置
}
interface CSBarcodeState {}
class CSBarcode extends React.Component<CSBarcodeProps, CSBarcodeState> {
constructor(props: CSBarcodeProps) {
super(props);
this.update = this.update.bind(this);
}
componentDidMount() {
this.update();
}
componentDidUpdate() {
this.update();
}
barcode: any;
handleBarcode = (r: any) => {
this.barcode = r;
};
update() {
const { options, value } = this.props;
JsBarcode(this.barcode, value, { ...options });
}
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="" />;
}
}
}
export default CSBarcode;
然后根据需要直接使用:
<CSBarcode
value={value}
options={{
format: 'CODE128', // 条形码类型
displayValue: false, // 否在条形码下方显示文字
}}
renderer="svg"
/>