import React, {Component} from 'react'
|
import PropTypes from 'prop-types'
|
import { is, fromJS } from 'immutable'
|
import JsBarcode from 'jsbarcode'
|
|
import './index.scss'
|
|
class BarCode extends Component {
|
static propTpyes = {
|
card: PropTypes.object, // 条码设置
|
value: PropTypes.any, // 条码值
|
}
|
|
state = {
|
error: false
|
}
|
|
componentDidMount () {
|
this.resetBarcode()
|
}
|
|
UNSAFE_componentWillReceiveProps (nextProps) {
|
if ((nextProps.value && this.props.value !== nextProps.value) || !is(fromJS(nextProps.card), fromJS(this.props.card))) {
|
this.setState({}, () => {
|
this.resetBarcode()
|
})
|
}
|
}
|
|
resetBarcode = () => {
|
const { value, card } = this.props
|
|
let style = card.style || {}
|
|
try {
|
JsBarcode(this.barcode, value, {
|
displayValue: card.displayValue === 'true',
|
width: card.interval || 1,
|
height: card.barHeight || 25,
|
margin: 0,
|
fontOptions: `${style.fontWeight || ''} ${style.fontStyle || ''}`,
|
textAlign: style.textAlign || 'left',
|
fontSize: (style.fontSize || 14) + 'px',
|
lineColor: style.color || '#000000'
|
})
|
this.setState({error: false})
|
} catch (e) {
|
this.setState({error: true})
|
}
|
|
}
|
|
render() {
|
const { error } = this.state
|
|
return (
|
<div className="barcode-box">
|
{error ? <span className="barcode-error">字符非法或过长!</span> : null}
|
<svg ref={(ref) => { this.barcode = ref }}/>
|
</div>
|
)
|
}
|
}
|
|
export default BarCode
|