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

react-date-range组件如何自定义左侧inputRanges预设时间范围

react-date-range自定义inputRanges预设范围解决方案

核心问题排查

配置不生效通常是以下3个原因导致:

  • 未将inputRanges属性传给正确的组件:仅DateRangePicker组件支持该属性,DateRange组件传入不会生效
  • 配置项缺失label字段:该字段控制左侧预设栏显示的选项文本,缺失时对应选项不会渲染
  • 未绑定ranges状态与onChange回调:预设选择后需要同步更新状态,组件才会响应选择结果

完整实现代码

依赖引入

import { useState } from 'react';
import { DateRangePicker } from 'react-date-range';
// 必须引入组件样式
import 'react-date-range/dist/styles.css';
import 'react-date-range/dist/theme/default.css';

组件实现(含「今年」「去年」「过去12个月」预设)

function CustomDateRangePicker() {
  // 绑定时间选择状态
  const [ranges, setRanges] = useState([
    {
      startDate: new Date(),
      endDate: new Date(),
      key: 'selection'
    }
  ]);

  // 自定义预设配置
  const customInputRanges = [
    {
      label: '今天',
      startDate: new Date(),
      endDate: new Date(),
      color: "#eecc99",
      key: "today",
      autoFocus: false,
      disabled: false,
      showDateDisplay: true,
    },
    {
      label: '今年',
      startDate: new Date(new Date().getFullYear(), 0, 1),
      endDate: new Date(),
      color: "#eecc99",
      key: "thisYear"
    },
    {
      label: '去年',
      startDate: new Date(new Date().getFullYear() - 1, 0, 1),
      endDate: new Date(new Date().getFullYear() - 1, 11, 31),
      color: "#eecc99",
      key: "lastYear"
    },
    {
      label: '过去12个月',
      startDate: new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
      endDate: new Date(),
      color: "#eecc99",
      key: "last12Months"
    }
  ]

  return (
    <DateRangePicker
      ranges={ranges}
      onChange={(item) => setRanges([item.selection])}
      inputRanges={customInputRanges}
    />
  )
}

额外说明

如果需要保留默认的「昨天」「上周」「上月」等预设,只需要把对应预设的配置项添加到customInputRanges数组中即可,不需要传入空数组清空原有预设。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:45:03