You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-datepicker中彻底移除不需要的时间选项?

如何在react-datepicker中彻底移除9:00-17:00之外的时间选项

你遇到的问题是minTime和maxTime只会将超出范围的时间置灰但仍显示,且自定义CSS隐藏无效。解决这个问题最直接的方式是使用react-datepicker提供的filterTime属性,从源头上过滤掉不需要的时间选项,而非依赖CSS隐藏。

修改后的代码

import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

const CustomTimePicker = () => {
  const [selectedTime, setSelectedTime] = useState(null);

  const handleTimeChange = (time) => {
    setSelectedTime(time);
  };

  // 过滤函数:只保留9:00到17:00的时间
  const filterTime = (time) => {
    const hour = time.getHours();
    // 包含9点和17点的时间
    return hour >= 9 && hour <= 17;
  };

  return (
    <DatePicker
      selected={selectedTime}
      className="datetime-text-input-small"
      onChange={handleTimeChange}
      showTimeSelect
      showTimeSelectOnly
      timeIntervals={60}
      timeCaption="Time"
      dateFormat="h:mm aa"
      placeholderText="Leave now"
      filterTime={filterTime} // 启用时间过滤
    />
  );
};

export default CustomTimePicker;

原理说明

filterTime是react-datepicker官方提供的时间过滤属性,它接收一个时间对象作为参数,返回true时该时间会被显示,返回false则直接不渲染这个时间选项。这种方式不需要依赖CSS,从根本上移除了不符合条件的时间,彻底解决置灰仍显示的问题。

至于你之前添加的CSS无效,大概率是样式优先级不足或者类名匹配问题(比如react-datepicker的动态样式覆盖了你的自定义CSS),但使用filterTime是更可靠的解决方案,无需处理样式冲突。

内容的提问来源于stack exchange,提问作者Anna1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 22:05:30