组件基于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