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

如何在react-date-range中获取选中的日期范围参数?

解决react-date-range中获取选中日期范围的问题

嘿,别着急!其实react-date-range的DateRangePicker组件的onChange回调会直接把选中的日期范围数据传给你的处理函数,只是你还没用到这个参数而已。我来帮你调整代码,轻松拿到startDate和endDate:

关键修改点

你只需要给handleSelect函数添加一个参数,这个参数就是组件返回的所有选中范围的集合,然后通过你定义的key(也就是selection)就能拿到对应的日期对象了。

完整示例代码

import { DateRangePicker} from 'react-date-range';
import 'react-date-range/dist/styles.css';
import 'react-date-range/dist/theme/default.css';

// 给handleSelect添加ranges参数
function handleSelect(ranges) {
  // 通过key"selection"获取选中的日期范围对象
  const selectedRange = ranges.selection;
  // 提取startDate和endDate
  const { startDate, endDate } = selectedRange;
  
  // 这里就可以对日期进行操作啦,比如打印看看
  console.log("开始日期:", startDate);
  console.log("结束日期:", endDate);
  
  // 如果需要格式化日期,比如转成YYYY-MM-DD格式
  const formattedStart = startDate.toISOString().split('T')[0];
  const formattedEnd = endDate.toISOString().split('T')[0];
  console.log("格式化后的开始日期:", formattedStart);
}

const selectionRange = { 
  startDate: new Date(), 
  endDate: new Date(), 
  key: 'selection', 
};

function App() {
  return (
    <div>
      <DateRangePicker ranges={[selectionRange]} onChange={handleSelect}/>
    </div>
  );
}

export default App;

简单解释

  • onChange回调会接收一个ranges对象,这个对象里的每个属性对应你传入ranges数组的每个范围(这里你只传了一个key为selection的范围,所以直接取ranges.selection)。
  • 每个范围对象里包含更新后的startDate、endDate和你定义的key,直接解构就能拿到你需要的日期参数。

这样你就能在handleSelect里自由操作选中的日期范围啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:47:54