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

React 18.2.0下React Day-Picker日期范围选择失效求解决方案

问题分析与修复方案

你的代码存在几个关键问题导致无法正常运行,以下是针对性的修复步骤:

  • 日期引用冲突:Date是引用类型,addDays(pastMonth, 4)会直接修改pastMonth本身,导致from和to指向同一个日期对象,破坏范围选择逻辑。
  • TypeScript语法混用(若使用JS环境):如果你的项目是纯JavaScript而非TypeScript,代码中的类型标注(如: DateRange、<DateRange | undefined>)会触发语法错误。
  • 缺失样式导入:React Day-Picker需要导入默认样式才能正确渲染日历界面,否则可能出现布局错乱。

修复后的代码

如果你使用TypeScript环境:

import React, { useState } from 'react';
import { addDays, format } from 'date-fns';
import { DateRange, DayPicker } from 'react-day-picker';
// 必须导入样式以正常渲染日历
import 'react-day-picker/dist/style.css';

const pastMonth = new Date();
const App = () => {
  // 复制新的Date对象避免引用冲突
  const defaultSelected: DateRange = {
    from: new Date(pastMonth),
    to: addDays(new Date(pastMonth), 4)
  };
  const [range, setRange] = useState<DateRange | undefined>(defaultSelected);
  
  let footer = <p>Please pick the first day.</p>;
  if (range?.from) {
    if (!range.to) {
      footer = <p>{format(range.from, 'PPP')}</p>;
    } else {
      footer = (
        <p>
          {format(range.from, 'PPP')}–{format(range.to, 'PPP')}
        </p>
      );
    }
  }
  return (
    <div>
      <DayPicker
        mode="range"
        defaultMonth={pastMonth}
        selected={range}
        footer={footer}
        onSelect={setRange}
      />
    </div>
  );
};

export default App;

如果你使用JavaScript环境:

import React, { useState } from 'react';
import { addDays, format } from 'date-fns';
import { DayPicker } from 'react-day-picker';
// 必须导入样式以正常渲染日历
import 'react-day-picker/dist/style.css';

const pastMonth = new Date();
const App = () => {
  // 复制新的Date对象避免引用冲突
  const defaultSelected = {
    from: new Date(pastMonth),
    to: addDays(new Date(pastMonth), 4)
  };
  const [range, setRange] = useState(defaultSelected);
  
  let footer = <p>Please pick the first day.</p>;
  if (range?.from) {
    if (!range.to) {
      footer = <p>{format(range.from, 'PPP')}</p>;
    } else {
      footer = (
        <p>
          {format(range.from, 'PPP')}–{format(range.to, 'PPP')}
        </p>
      );
    }
  }
  return (
    <div>
      <DayPicker
        mode="range"
        defaultMonth={pastMonth}
        selected={range}
        footer={footer}
        onSelect={setRange}
      />
    </div>
  );
};

export default App;

额外检查项

  1. 确认依赖版本:确保package.json中react-day-picker版本为^8.0.0或更高,date-fns版本为^2.0.0或更高。
  2. 若使用TypeScript,确保tsconfig.json中jsx配置为react-jsx(适配React 18)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:11:28