react 封装jsbarcode 组件

组件基于jsbarcode 需先引入 jsbarcode

npm install jsbarcode --save
yarn add jsbarcode
import React, { Component } from 'react';
import JsBarcode from 'jsbarcode';
import PropTypes from 'prop-types';

export default class Barcode extends Component {

  static defaultProps = {
    format: 'CODE128',
    renderer: 'svg',
    width: 2,
    height: 100,
    displayValue: true,
    textAlign: 'center',
    textPosition: 'top',
    textMargin: 6,
    fontSize: 20,
    background: '#ffffff',
    lineColor: '#000000',
    margin: 10,
    marginBottom: 24,
  };

  static propTypes = {
    value: PropTypes.string.isRequired,
    renderer: PropTypes.string,
    format: PropTypes.string,
    width: PropTypes.number,
    height: PropTypes.number,
    displayValue: PropTypes.bool,
    textAlign: PropTypes.string,
    textPosition: PropTypes.string,
    textMargin: PropTypes.number,
    fontSize: PropTypes.number,
    background: PropTypes.string,
    lineColor: PropTypes.string,
    margin: PropTypes.number,
    marginBottom: PropTypes.number,
  };

  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="" />
      );
    }
  };
}

用法:

import React, { Component } from 'react';
import Barcode from "../components/Barcode";

class codeList extends Component {
  render() {
    return (
      <Barcode value="12345678" />
    );
  }
}

export default codeList;

jsbarcode文档:https://github.com/lindell/JsBarcode

转载于:https://my.oschina.net/u/3125136/blog/3061622

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值