1. 开发环境 react16+antd4
2. 电脑系统 windows11 专业版
3. 分享一下 react+antd RangePicker 组件的工夫禁选; 废话不多说, 间接上代码:
const [dateType, setdataType] = useState([
{
value: '按日',
key: 1
},
{
value: '按月',
key: 2
}
]);
const [dateTime, setDateTime] = useState([moment().add(-1, 'years').add(0, "months").format("YYYY-MM"),
moment().format("YYYY-MM"),
]);
const [timeValue, setTimeValue] = useState([moment(moment().add(-1, 'years').add(0, "months"), 'YYYY-MM'),
moment(moment(), 'YYYY-MM')
]);
const [timeFormat, setTimeFormat] = useState('YYYY-MM');
const [pickerValue, setPickerValue] = useState('month');
const getDay = () => {
setDateTime([moment().add(-1, "months").format("YYYY-MM-DD"),
moment().format("YYYY-MM-DD"),
]);
setTimeValue([moment(moment().add(-1, "months"), 'YYYY-MM-DD'),
moment(moment(), 'YYYY-MM-DD')
]);
setTimeFormat('YYYY-MM-DD');
setPickerValue('date');
};
const getMonth = () => {
setDateTime([moment().add(-1, 'years').add(0, "months").format("YYYY-MM"),
moment().format("YYYY-MM"),
]);
setTimeValue([moment().add(-1, 'years').add(0, "months"),
moment(moment(), 'YYYY-MM')
]);
setTimeFormat('YYYY-MM');
setPickerValue('month');
}
// 工夫类型 变动
const TimeTypeChange = (value, option) => {setdateTypeValue(value);
switch (+value) {
case 1:// 按日
getDay();
break;
case 2:// 按月
getMonth();
break;
}
}
const timeDisabled = (current) => {switch (+dateTypeValue) {
case 1:// 按日
return day_disabledDate(current);
break;
case 2:// 按月
return month_disabledDate(current);
break;
}
}
const month_disabledDate = (current) => {if (!timeValue) {return false;}
const tooLate = timeValue[0] && current.diff(timeValue[0], 'months') > 11;
const tooEarly = timeValue[1] && timeValue[1].diff(current, 'months') > 11;
return !!tooEarly || !!tooLate;
};
const day_disabledDate = (current) => {if (!timeValue) {return false;}
const tooLate = timeValue[0] && current.diff(timeValue[0], 'months') > 0;
const tooEarly = timeValue[1] && timeValue[1].diff(current, 'months') > 0;
const disable_day = current && current < moment().endOf('day');
return !!tooEarly || !!tooLate || !disable_day;
}
const onOpenChange = (open) => {if (open) {setTimeValue([null, null]);
}
};
const _onRangePickerChange = (date, dateString) => {// setTimeValue(dateString);
setTimeValue(date);
setDateTime(dateString);
}
const onCalendarChange = (value) => {setTimeValue(value);
}
<Select placeholder='请抉择工夫类型'
value={dateTypeValue == 1 ? '按日' : '按月'}
onChange={TimeTypeChange}
getPopupContainer={triggerNode => triggerNode.parentElement}>
{dateType && dateType.map((item) => {
return (<Option key={item.key} value={item.key}>{item.value}</Option>
)
})}
</Select>
<RangePicker
style={{width: 330, marginLeft: 5}}
value={timeValue}
format={timeFormat}
allowClear={false}
disabledDate={timeDisabled}
picker={pickerValue}
onChange={_onRangePickerChange}
onOpenChange={onOpenChange}
onCalendarChange={onCalendarChange}
/>
4. 成果如下:
// 默认 显示按月
// 抉择按日禁选 成果
// 按月禁选
// 按日禁选
5. 本期的分享到了这里就完结啦, 心愿对你有所帮忙, 让咱们一起致力走向巅峰。