import React, {Component} from 'react'
|
import PropTypes from 'prop-types'
|
import { is, fromJS } from 'immutable'
|
import { Select, Input } from 'antd'
|
|
import MKEmitter from '@/utils/events.js'
|
import './index.scss'
|
|
const { Option } = Select
|
|
class StyleInput extends Component {
|
static propTpyes = {
|
config: PropTypes.object,
|
onChange: PropTypes.func,
|
}
|
|
state = {
|
value: '',
|
unit: '',
|
options: []
|
}
|
|
UNSAFE_componentWillMount () {
|
const { config } = this.props
|
|
let val = config.initval || config.initVal || ''
|
let options = config.options || ['px', 'vh', 'vw', '%']
|
let unit = options[0]
|
|
if (val && typeof(val) === 'string') {
|
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))
|
}
|
|
componentDidMount () {
|
MKEmitter.addListener('mkFC', this.mkFormHandle)
|
}
|
|
componentWillUnmount () {
|
this.setState = () => {
|
return
|
}
|
MKEmitter.removeListener('mkFC', this.mkFormHandle)
|
}
|
|
mkFormHandle = (type, field, value) => {
|
if (field !== this.props.config.field) return
|
|
if (type === 'input') {
|
let val = value
|
let unit = this.state.unit
|
|
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, unit})
|
|
this.props.onChange(value, true)
|
}
|
}
|
|
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
|