React Hooks应用antd中 DatePicker组件设置默认值
按照需求实现年月日时分截至至当前时间
页面效果呈现出来了,可是仍有bug
未点击选中当前日期的话,我们手动选择时分就会出现当前的时分与当下时间不匹配,本来想用组件内部的方法解决,让时分秒面板显示禁止图标,奈何没找到方法
出现的问题效果图如下:
这里如果我们不去选中当前日期,而是先选择小时分钟且大于当前时分的数字,就会出现可以选择未来时间,这并不是我想要的效果,而且我一选中才会显示禁止哪些时分,但赋值已经出错了,页面禁止也无用
针对这个问题自己做了优化
最后,干脆赋值一个默认时间,它就不会出现时分选择大于当前时分解决方法如下:
//需引入moment.js
import moment from "moment";
const date=new Date()
// 此处代码实现仅为部分展示
<Form.Item
className="number"
validateTrigger="onBlur"
name="faultDate"
rules={[
{
required: true,
message: "请选择问题发生时间",
},
]}
initialValue={moment(date,'YYYY-MM-DD HH:mm')}
>
// disabledTime 与 showTime 一起使用
<DatePicker
disabledDate={disabledDate}
disabledTime={disabledTime}
className='datePicker'
format="YYYY-MM-DD HH:mm"
showTime
onChange={(value) => handleDateChange(value)}
/>
</Form.Item>
对应的事件
// 禁止大于当前的日期
const disabledDate = (current) => {
return current && moment().endOf('day') < current;
};
//循环数组
const range = (start, end) => {
const result = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
}
// 禁止大于当前时分
const disabledTime = (current) => {
const hours = moment().hours();
const minutes = moment().minutes();
const currentHour = moment(current).hour();
if (current && moment(current).date() === moment().date()) {
return {
disabledHours: () => range(0, 24).splice(hours+1, 24-hours),
disabledMinutes: () => {
if (currentHour === hours) {
return range(0, 60).splice(minutes+1, 60-minutes);
}else {
return [];
}
},
}
}else {
return {
disabledHours: () => [],
disabledMinutes: () => [],
}
}
}
效果图如下:
我们页面已经显示了当前的年月日时分,打开时间面板时间也默认当前时间,效果正如我想要实现的