我想知道如何禁用小时和分钟,考虑当前时间而不是过去几个小时。
const disabledHours = () => {
const hours = [];
for (let i = 0; i < moment().hour(); i += 1) hours.push(i);
return hours;
};
const disabledMinutes = (selectedHour) => {
const minutes = [];
if (selectedHour === moment().hour()) {
for (let i = 0; i < moment().minute(); i += 1) minutes.push(i);
}
return minutes;
};
<TimePicker
disabledHours={disabledHours}
disabledMinutes={disabledMinutes}
format="h:mm a"
style={{ width: '100%' }}
disabled={isLoading}
/>
如果您想禁用未来时间:
const disabledHours = () => {
const hours = [];
const currentHour = moment().hour();
for (let i = currentHour + 1; i <= 24; i++) {
hours.push(i);
}
return hours;
};
const disabledMinutes = (selectedHour) => {
const minutes = [];
const currentMinute = moment().minute();
if (selectedHour === moment().hour()) {
for (let i = currentMinute; i <= 60; i++) {
minutes.push(i);
}
}
return minutes;
};
演示:https://codesandbox.io/s/antd-reproductive-template-forked-uslk0?file=/index.js
为了避免切换 AM 或 PM 时出现问题,您可以编写任何关于如何设置
onSelect
回调的最大时间参考的逻辑,例如:
const TimeComponent = () => {
const [selectedTime, setSelectedTime] = useState(moment());
const disabledHours = () => {
const hours = [];
const currentHour = moment().hour();
for (let i = currentHour + 1; i <= 24; i++) {
hours.push(i);
}
return hours;
};
const disabledMinutes = (selectedHour) => {
const minutes = [];
const currentMinute = moment().minute();
if (selectedHour === moment().hour()) {
for (let i = currentMinute + 1; i <= 60; i++) {
minutes.push(i);
}
}
return minutes;
};
const onSelect = (time) => {
if (time.isAfter(moment())) {
console.log("ping");
setSelectedTime(moment());
return;
}
setSelectedTime(time);
};
return (
<TimePicker
onSelect={onSelect}
disabledHours={disabledHours}
disabledMinutes={disabledMinutes}
format="h:mm a"
value={selectedTime}
style={{ width: "100%" }}
use12Hours={true}
/>
);
};
我用案例来面对这个问题
您可以将 12 替换为当前分钟 - 通过 new Date().getMinutes(); 获取它 或按时刻 moment().min(); 或按 dayJs dayjs().min();
<TimePicker
disabledTime={() => ({
disabledHours: () =>
Array.from({ length: 24 }, (_, i) => (i >= 1 ? i : i - 1)),
disabledMinutes: () =>
Array.from({ length: 60 }, (_, i) =>
i >= 12 + 1
? i
: i - (12 + 1)
),
})}
/>