需求场景: 只能选择一个月区间 31天,并且只能选择当天之前的,并且往前时间不超过一年。假设一个模块内多个页面有这个需求,需要统一。
封装目的效果,不用写重复判断以及冗余的函数,保持通用便捷性。
最终效果:
源码:
import React, { useEffect, useState } from 'react'
import { DatePicker, } from 'antd'
import moment from 'moment'
const { RangePicker } = DatePicker
const WrapRangePickerHoc = ({ value: propsValue, onChange }) => {
const [dates, setDates] = useState([])
const [hackValue, setHackValue] = useState()
const [value, setValue] = useState(propsValue)
// 只能选择一个月区间 31天,并且只能选择当天之前的,往前时间不超过一年
const rangeDisableDate = (currentDate) => {
const onlyOnlyYear = currentDate && currentDate < moment().subtract(1, 'years')
const onlyToday = currentDate && currentDate > moment().endOf('day')
if (!dates || dates.length === 0) {
return onlyToday || onlyOnlyYear
}
const tooLate = dates[0] && currentDate.diff(moment(dates[0]), 'days') > 31
const tooEarly = dates[1] && moment(dates[1]).diff(currentDate, 'days') > 31
return tooEarly || tooLate || onlyOnlyYear || onlyToday
}
const onOpenChange = open => {
if (open) {
setHackValue([])
setDates([])
} else {
setHackValue(undefined)
}
}
useEffect(() => {
setValue(propsValue)
}, [propsValue])
const handleOnChange = (val, dateStr) => {
onChange(val, dateStr)
}
return (
<RangePicker
allowClear={false}
value={hackValue || value}
disabledDate={rangeDisableDate}
onCalendarChange={val => setDates(val)}
onChange={handleOnChange}
onOpenChange={onOpenChange}
/>
)
}
export default WrapRangePickerHoc
调用如下,只需要传入默认值,和回调事件就可以,不用每次使用都写禁止选用日期的条件:
import React, { Component } from 'react'
class IndexReset extends Component {
constructor(props) {
super(props)
this.state = {
value: [],
}
}
handlePicker = (date, dateStr) => {
//.......
}
render() {
const { value,} = this.state
return (
<RangePickerHoc onChange={this.handlePicker} value={value}/>
)
}
}
export default IndexReset