React中使用antd RangePicker限制日期选择

本文介绍如何在React中使用Ant Design的RangePicker组件来限制用户选择的日期范围,包括仅能选择过去日期、未来日期及限定日期区间等场景,并提供具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景

React中使用antd RangePicker限制日期选择,有下面一些场景:

1、今天之前的日期不可选择(不包括今天)

disabledDate = (_current) => {
    let current = _current.format('YYYY-MM-DD')
    return current && current < moment().endOf('day').format('YYYY-MM-DD')
}

2、今天之前的日期不可选择(包括今天)

disabledDate = (_current) => {
    let current = _current.format('YYYY-MM-DD')
    return current && current <= moment().endOf('day').format('YYYY-MM-DD')
}

3、今天之后的日期不可选择(不包括今天)

disabledDate = (_current) => {
    let current = _current.format('YYYY-MM-DD')
    return current && current > moment().endOf('day').format('YYYY-MM-DD')
}

4、今天之后的日期不可选择(包括今天)

disabledDate = (_current) => {
    let current = _current.format('YYYY-MM-DD')
    return current && current >= moment().endOf('day').format('YYYY-MM-DD')
}

5、选择不超过7天的范围(重点)

disabledDate = (_current) => {
    const { dates } = this.state
    if (!dates || dates.length === 0) {
        return false
    }
    const tooLate = dates[0] && _current.diff(dates[0], 'days') > 6
    const tooEarly = dates[1] && dates[1].diff(_current, 'days') > 6
    return !!tooEarly || !!tooLate
}

6、选择不超过7天的范围以及今天之后的日期不可选择(包括今天)(重点)

disabledDate = (_current) => {
    const { dates } = this.state
    const current = _current.format('YYYY-MM-DD')
    const dayDate = current && current >= moment().endOf('day').format('YYYY-MM-DD')
    if (!dates || dates.length === 0) {
        return dayDate
    }
    const tooLate = dates[0] && _current.diff(dates[0], 'days') > 6
    const tooEarly = dates[1] && dates[1].diff(_current, 'days') > 6
    return !!tooEarly || !!tooLate || dayDate
}

应用

源码

<RLRangePicker
    locale={locale}
    format='YYYY-MM-DD'
    style={{ marginLeft: 10 }}
    key='time'
    disabledDate={this.disabledDate}
    onCalendarChange={val => {
        this.setState({ dates: val })
    }}
    onChange={this.rangeDateChange}
    onOpenChange={this.onOpenChange}
    value={this.state.dates || this.state.value}
/>

rangeDateChange = (moments, dates) => {
    this.setState({
        value: moments
    })
}

// 弹出日历和关闭日历的回调
onOpenChange = (open) => {
    if (open) {
        this.setState({ dates: [null, null] })
    } else {
        this.setState({ dates: null })
    }
}

在这里插入图片描述
选择范围为7天且不能选择今天及之后的日期。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值