场景
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天且不能选择今天及之后的日期。