React JsBarcode使用

2,940 阅读1分钟

瞎扯

百度,google搜了一下,发现很多教怎么用的,就是没有封装组件的.

实际这个东西,用起来还是很简单的.

今天正好封装了个组件.

今天算是写react的第三个月了.react还是比较好上手的.

JsBarcode

几种应用:

image.png

这种是JQuery的.明显不是想要的,略过


image.png

这种用classname找的方法.感觉不好.


image.png
这种有点不明白.看起来也不是想要的.


image.png

最后这个才像是需要的.

封装

import React, { Component } from 'react';
import * as Barcode from 'jsbarcode';

/**
 * 简单生成条形码
 * {
 * width: 2,//较细处条形码的宽度
 * height: 100, //条形码的宽度,无高度直接设置项,由位数决定,可以通过CSS去调整,见下
 * quite: 10,
 * format: "CODE128",
 * displayValue: false,//是否在条形码下方显示文字
 * font:"monospace",
 * textAlign:"center",
 * fontSize: 12,
 * backgroundColor:"",
 * lineColor:"#000"//条形码颜色
 * }
 */
class SimpleBarcode extends Component {
    componentDidMount() {
        this.createBarcode();
    }

    componentDidUpdate() {
        // if (this.props !== nextProps) {
        this.createBarcode();
        // }
    }

    createBarcode = () => {
        if (!this.barcode) return;
        const {
            width = 1, height = 35, margin = 0, label, displayValue = true,
        } = this.props;
        if (!label) {
            return;
        }
        Barcode(this.barcode, label, {
            displayValue,
            width,
            height,
            margin,
        });
    };

    render() {
        const {
            labelClassName, label, labelStyle, className, style, displayValue = true,
        } = this.props;
        return (
            <div className={className} style={style}>
                <svg
                    ref={(ref) => {
                        this.barcode = ref;
                    }}
                />
                {displayValue ? null : <p className={labelClassName} style={labelStyle}>{label}</p>}
            </div>
        );
    }
}

export default SimpleBarcode;

简单使用


 <SimpleBarcode
      height={80}
      width={2}
      label={123123}
  /> 

期待你的评论,点赞