import React, { Component } from 'react'
|
import { is, fromJS } from 'immutable'
|
import { DatePicker } from 'antd'
|
import moment from 'moment'
|
|
const { MonthPicker, WeekPicker, RangePicker } = DatePicker
|
|
/**
|
* @description 自定义时间选择器
|
*/
|
class MkDatePicker extends Component {
|
constructor(props) {
|
super(props)
|
|
const config = props.config
|
|
let mode = 'date'
|
let format = 'YYYY-MM-DD'
|
|
if (config.type === 'datemonth') {
|
mode = 'month'
|
format = 'YYYY-MM'
|
} else if (config.type === 'week') {
|
mode = 'week'
|
format = 'YYYY-MM-DD'
|
} else if (config.type === 'daterange') {
|
mode = 'daterange'
|
format = 'YYYY-MM-DD'
|
}
|
let value = config.initval || null
|
|
if (mode === 'daterange') {
|
if (value) {
|
let val = value.split(',')
|
value = [moment(val[0], format), moment(val[1], format)]
|
} else {
|
value = [null, null]
|
}
|
} else if (value) {
|
value = moment(value, format)
|
}
|
|
this.state = {
|
value,
|
mode,
|
format
|
}
|
}
|
|
shouldComponentUpdate (nextProps, nextState) {
|
return !is(fromJS(this.state), fromJS(nextState))
|
}
|
|
componentWillUnmount () {
|
this.setState = () => {
|
return
|
}
|
}
|
|
onChange = (val) => {
|
const { format, mode } = this.state
|
|
this.setState({value: val})
|
|
if (mode === 'daterange') {
|
let _val = val
|
if (_val && !_val[0]) {
|
_val = ''
|
}
|
this.props.onChange(_val ? `${moment(_val[0]).format(format)},${moment(_val[1]).format(format)}` : '')
|
} else {
|
this.props.onChange(val ? moment(val).format(format) : '')
|
}
|
}
|
|
render() {
|
const { value, mode } = this.state
|
|
if (mode === 'date') {
|
return <DatePicker value={value} onChange={this.onChange}/>
|
} else if (mode === 'month') {
|
return <MonthPicker value={value} onChange={this.onChange}/>
|
} else if (mode === 'week') {
|
return <WeekPicker value={value} onChange={this.onChange}/>
|
} else if (mode === 'daterange') {
|
return <RangePicker placeholder={['开始日期', '结束日期']} value={value} onChange={this.onChange}/>
|
}
|
}
|
}
|
|
export default MkDatePicker
|