React使用jsbarcode条形码插件

今天来记录一下jsbarcode条形码使用方法,希望能给有需要的同学一些帮助,当然也是为了方便自己,哈哈哈~~

既然是插件,当然是要先安装喽,命令走起~

1
npm install jsbarcode --save

我这边为了方便管理,直接写了一个小组件,然后创建一个js文件Barcode.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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="" />
      );
    }
  };
}

这个组建就完成啦,代码很简单,使用的就是canvas,外加一些属性,看一下应该就明白啦。需要的同学直接复制就OK

接下来就是引用组件啦,在你需要放条形码的页面按照下面的方式引用就可以:
在这里插入图片描述在这里插入图片描述

1
<Barcode value={listInfo.emsOrderId} height={42} width={1.9} />

里面的属性就是BarCode文件this.props的参数,需要哪个加哪个,方便极了。

感觉好像也没说什么,哈哈哈~大家凑合着看,有什么疑问或者不对的地方,欢迎指出来哟,吼~吼~元气满满!!!!!