功能:默认选中当天,选中范围三个月内,选中最长天数7天
具体方法:(自定义ahooks)
const useTime = () => {
const format = "YYYY-MM-DD HH:mm:ss";
const [dates, setDates] = useState([]);
const [hackValue, setHackValue] = useState();
// 默认当天
const [timevalue, settimeValue] = useState([moment(util.getNowTime() + " 00:00:00", format), moment(util.getNowTime() + " 23:59:59", format)]);
const disabledDate = (time: any) => {
if (!time) {
return false
} else {
//限制三个月内
const timeRange = time < moment().subtract(3, 'month') || time > moment().add(3, 'm');
//只能选择七天
const tooLate = dates[0] && time.diff(dates[0], 'days') > 7;
const tooEarly = dates[1] && (dates[1] as any).diff(time, 'days') > 7;
return timeRange || tooEarly || tooLate;
}
};
const onOpenChange = (open: boolean) => {
if (open) {
const arr: any = [];
setHackValue(arr);
setDates([]);
} else {
setHackValue(undefined);
}
};
return { format, disabledDate, onOpenChange, timevalue, settimeValue, hackValue, setDates };
}
具体使用:
const { format, disabledDate, onOpenChange, timevalue, settimeValue, hackValue, setDates } = useTime();
<Form.Item label="事件日期" >
<RangePicker
// @ts-ignore
value={hackValue || timevalue} showTime format={format}
disabledDate={disabledDate} allowClear={false}
onCalendarChange={(val: any) => setDates(val)}
onChange={(val: any) => settimeValue(val)}
onOpenChange={onOpenChange}
/>
</Form.Item>
效果图: