king
2021-09-01 31ec63f0419895876cbaba99637a884a32d33d0d
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
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