king
2021-07-12 ca788834ea15d6dd43bf0923757ca1d46d00ebc4
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { is, fromJS } from 'immutable'
import { Select, Input } from 'antd'
 
import './index.scss'
 
const { Option } = Select
 
class StyleInput extends Component {
  static propTpyes = {
    defaultValue: PropTypes.any,
    options: PropTypes.any,
    value: PropTypes.any,
    onChange: PropTypes.func,
  }
 
  state = {
    value: '',
    unit: '',
    options: null
  }
 
  UNSAFE_componentWillMount () {
    const { value, options } = this.props
 
    let val = ''
    let unit = ''
 
    if (value !== undefined) {
      val = value
    }
 
    unit = options[0]
 
    if (val) {
      if (val.indexOf('px') > -1) {
        unit = 'px'
      } else if (val.indexOf('%') > -1) {
        unit = '%'
      } else if (val.indexOf('vw') > -1) {
        unit = 'vw'
      } else if (val.indexOf('vh') > -1) {
        unit = 'vh'
      }
    }
 
    let _val = parseFloat(val)
 
    if (isNaN(_val)) {
      _val = ''
    }
 
    this.setState({value: _val, options: options, unit})
  }
 
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.state), fromJS(nextState))
  }
 
  /**
   * @description 组件销毁,清除state更新,清除快捷键设置
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
  }
 
  changeValue = (e) => {
    const { unit } = this.state
    let val = e.target.value
 
    if (/\d+\.$/.test(val)) {
      this.setState({
        value: val
      })
      return
    }
    let _val = parseFloat(val)
    
    if (isNaN(_val)) {
      _val = ''
    }
 
    this.setState({
      value: _val,
    })
 
    this.props.onChange(_val ? `${_val}${unit}` : '')
  }
 
  changeUnit = (val) => {
    const { value } = this.state
 
    this.setState({unit: val})
    this.props.onChange(value ? `${value}${val}` : '')
  }
 
  render () {
    const { value, options, unit } = this.state
 
    return (
      <div className="style-input-wrap">
        <Input value={value} addonAfter={
          options.length > 1 ?
          <Select value={unit} onChange={this.changeUnit}>
            {options.map(item => <Option key={item} value={item}>{item}</Option>)}
          </Select> :
          <div className="single-unit">{unit}</div>
        } onChange={this.changeValue}/>
      </div>
    )
  }
}
 
export default StyleInput