最近在做和时间段范畴相干的,预设罕用的日期范畴能够进步用户体验。能够说 antd 的组件是很不错的,然而美中不足的是,不反对预设范畴回填选中,怎么办?
在此基础上封装一下好了。
先来看下效果图:
未选中:
选中回填:
看了下渲染进去的 html 内容,用的是 Tag
实现的。那我也这么实现好了。
次要是利用 RangePicker
的 renderExtraFooter
进行解决。如果回填值和预设值统一,就设置选中,否则就不选中。
还有一个要害的点:就是选中预设的 tag
后,须要 敞开 日期抉择弹窗。所以还须要额定的解决 open
。
具体实现看上面代码:
// rangePicker.tsx
import React, {forwardRef} from 'react'
import {Tag, DatePicker} from 'antd';
import {useState} from 'react';
import {RangePickerProps, RangePickerValue} from 'antd/lib/date-picker/interface';
const {RangePicker} = DatePicker
const Index = ({value, ranges = {}, onChange, open, format = "YYYY-MM-DD", ...props}: RangePickerProps, ref: any) => {const [val, setVal] = useState(value)
const [show, setShow] = useState(open)
const isDateSame = (key: string) => {const [start, end] = ranges[key] as RangePickerValue
return val && val.length && start && end ? start.isSame(val[0]) && end.isSame(val[1]) : false
}
const tagCheck = (key: string) => () => {setVal(ranges[key])
const [start, end] = ranges[key] as RangePickerValue
onChange && onChange(ranges[key] as RangePickerValue, [start ? start.format(format as string) : '', end ? end.format(format as string) :''])
setShow(false)
}
const footRanges = () => (
<div className="range-quick-selector">
{Object.keys(ranges).map(key => (<Tag key={key} onClick={tagCheck(key)} color={isDateSame(key) ? 'blue' : ''}>{key}</Tag>
))}
</div>
)
const onOpenChange = (status: boolean) => {setShow(status)
}
const onChangeFn = (dates: RangePickerValue, dateStrings: [string, string]) => {onChange && onChange(dates, dateStrings)
setVal(dates)
}
return (
<RangePicker
renderExtraFooter={footRanges}
value={val}
onChange={onChangeFn}
onOpenChange={onOpenChange}
open={show}
format={format}
{...props}
/>
)
}
export default forwardRef(Index)
怎么用呢?原来怎么应用,当初就怎么应用:
import React, {useState} from 'react'
import moment from 'moment';
import {RangePickerValue, RangePickerPresetRange} from 'antd/lib/date-picker/interface';
import RangePicker from './rangePicker'
const ranges: {[range: string]: RangePickerPresetRange } = {'明天': [moment(), moment()],
'昨天': [moment().subtract('days', 1), moment().subtract('days', 1)],
'近一周': [moment().subtract('days', 7), moment()],
'近两周': [moment().subtract('days', 14), moment()],
'近一个月': [moment().subtract('days', 30), moment()],
'近三个月': [moment().subtract('days', 90), moment()],
'近半年': [moment().subtract('days', 182), moment()], // 一年的一半
'近一年': [moment().subtract('days', 365), moment()],
'当月': [moment().startOf('month'), moment()],
'当季': [moment().startOf('quarter'), moment()],
'当年': [moment().startOf('year'), moment()],
}
const demo = () => {const [dateRange, setDateRange] = useState<RangePickerValue>([])
const rangePickerChange = (dates: RangePickerValue, dateStrings: [string, string]) => {console.log({dates, dateStrings});
setDateRange(dates)
}
return <RangePicker value={dateRange} onChange={rangePickerChange} ranges={ranges} />
}