likes
comments
collection
share

react+antd日期选择限制

作者站长头像
站长
· 阅读数 24

1.开发环境 react2.电脑系统 windows11专业版3.在开发的过程中,我们可能会需要时间限制,下面我来分享一下方法,希望对你有所帮助。4.废话不多说,直接上代码:

{
    dateTypeValue == 2 ? <RangePicker picker="month" onChange={(dates, dateStrings) => {
    setDateTime(dateStrings)
}} onCalendarChange={(val) => setDateTimeValue(val)}   allowClear={false} getPopupContainer={triggerNode => triggerNode.parentElement} value={dateTimeValue} disabledDate={month_disabledDate} onOpenChange={onOpenChange} /> :
<RangePicker onChange={(dates, dateStrings) => {
    setDateTime(dateStrings)
}} allowClear={false} onCalendarChange={(val) => setDateTimeValue(val)} getPopupContainer={triggerNode => triggerNode.parentElement} value={dateTimeValue} disabledDate={day_disabledDate} onOpenChange={onOpenChange}/>
}
// 注意:这里是通过 dateTypeValue的值来判断展示 月日期 还是 具体日 日期
const [dateTimeValue,setDateTimeValue] = useState(null);
/* 日期禁用 处理 */
    const month_disabledDate = (current) => {
        if (!dateTimeValue) {
            return false;
        }

        const tooLate = dateTimeValue[0] && current.diff(dateTimeValue[0], 'months') > 11;
        const tooEarly = dateTimeValue[1] && dateTimeValue[1].diff(current, 'months') > 11;
        return !!tooEarly || !!tooLate;
    };

    const day_disabledDate = (current)=>{
        if (!dateTimeValue) {
            return false;
        }

        const tooLate = dateTimeValue[0] && current.diff(dateTimeValue[0], 'days') > 30;
        const tooEarly = dateTimeValue[1] && dateTimeValue[1].diff(current, 'days') > 30;
        return !!tooEarly || !!tooLate;
    }



    const onOpenChange = (open) => {
        if (open) {
            setDateTimeValue([null, null]);
        }
    };

5.关键代码:

onCalendarChange={(val) => setDateTimeValue(val)}
value={dateTimeValue} 
disabledDate={month_disabledDate} 
onOpenChange={onOpenChange}

6.月效果如下:react+antd日期选择限制

7.日效果如下:react+antd日期选择限制

8.扩展:

const DisabledDate = (current) => {
    // // 限制为前后一周
    // return current < moment().subtract(7, "days") || current > moment().add(7, 'days')
    // 限制为前后一周
    // return current < moment().subtract(1, "weeks") || current > moment().add(1, 'weeks')
    // 限制为前后一月
    // return current < moment().subtract(1, "months") || current > moment().add(1, 'months')
    // 限制为前后一年
    // return current < moment().subtract(1, "years") || current > moment().add(1, 'years')

    // // 限制为前后12月
    return current < moment().subtract(12, "months") || current > moment().add(12, 'months')
}

9.本期的分享到了这里就结束啦,希望对你有所帮助,让我们一起努力走向巅峰。