如何使用时间选择器 antd 从现在开始禁用时间

How to disable time from now with time picker antd

我想知道如何禁用小时和分钟,同时考虑当前时间而不是过去的时间。

  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-reproduction-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}
    />
  );
};