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

如何在react-datepicker的时间选择下拉菜单中添加选中对勾图标

实现方案

下面提供两种可直接落地的实现方式,可根据你的需求选择:

方案1:CSS伪元素实现(无侵入,改造成本最低)

react-datepicker的选中状态时间项默认带有react-datepicker__time-list-item--selected类名,可直接通过CSS插入对勾,无需修改组件逻辑:

/* 给所有时间选项预留右侧图标位 */
.react-datepicker__time-list-item {
  position: relative;
  padding-right: 30px !important;
}
/* 选中项追加对勾图标 */
.react-datepicker__time-list-item--selected::after {
  content: "✓";
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #1677ff;
  font-weight: 600;
}

如果需要使用自定义图标资源,替换content属性为background-image相关配置即可。

方案2:自定义渲染时间列表(支持复杂自定义逻辑)

如果需要使用自定义图标组件、或要附加其他交互逻辑,可以使用库内置的renderTimeListContents属性自定义时间项渲染:

import { useState } from 'react';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
// 引入你的自定义对勾图标,也可以直接写SVG代码
import CheckIcon from './CheckIcon';

export default function TimePickerWithCheck() {
  const [startDate, setStartDate] = useState(new Date());

  const customRenderTimeList = ({ times, handleClick }) => {
    return (
      <ul className="react-datepicker__time-list">
        {times.map((time, idx) => {
          const isSelected = time.getTime() === startDate.getTime();
          return (
            <li
              key={idx}
              className={`react-datepicker__time-list-item ${isSelected ? 'react-datepicker__time-list-item--selected' : ''}`}
              onClick={() => handleClick(time)}
            >
              {time.toLocaleTimeString([], { 
                hour: 'numeric', 
                minute: '2-digit', 
                hour12: true 
              })}
              {isSelected && <CheckIcon style={{ marginLeft: '10px', color: '#1677ff' }} />}
            </li>
          )
        })}
      </ul>
    )
  }

  return (
    <DatePicker
      selected={startDate}
      onChange={(date) => setStartDate(date)}
      shouldCloseOnSelect={false}
      showTimeSelect
      showTimeSelectOnly
      timeIntervals={15}
      dateFormat="h:mm aa"
      renderTimeListContents={customRenderTimeList}
    />
  )
}

如果只是单纯需要加对勾图标优先选方案1,有复杂定制需求选方案2即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 07:12:02