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

如何使用react-dates库实现日历垂直滚动功能?

React-Dates 移动端垂直滚动日历实现方案

针对你使用DateRangePicker实现移动端垂直滚动日历的需求,结合官方垂直滚动示例的核心逻辑,下面是具体的调整方案:

核心问题分析与修改点

  1. 响应式逻辑动态更新
    你当前的orientation、withFullScreenPortal等变量仅在组件初始化时计算一次,窗口大小变化(比如手机旋转)时不会自动同步状态,需要通过监听媒体查询来实时更新。

  2. 开启垂直滚动开关
    官方垂直滚动示例依赖scrollable={true}属性,你的代码里缺少这个配置——这是垂直滚动功能生效的关键开关。

  3. 移动端滚动体验优化
    12个月的垂直日历需要限制容器高度,避免页面过度拉伸,确保日历在可视区域内独立滚动。

修改后的完整代码

import { useState, useEffect } from "react";
import { DateRangePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

function DataPicker() {
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [focusedInput, setFocusedInput] = useState(null);
  const [isMobile, setIsMobile] = useState(window.matchMedia("(max-width: 768px)").matches);

  const handleDatesChange = ({ startDate, endDate }) => {
    setStartDate(startDate);
    setEndDate(endDate);
  };

  // 监听窗口尺寸变化,同步移动端状态
  useEffect(() => {
    const mediaQuery = window.matchMedia("(max-width: 768px)");
    const handleMediaChange = (e) => setIsMobile(e.matches);
    
    mediaQuery.addEventListener("change", handleMediaChange);
    return () => mediaQuery.removeEventListener("change", handleMediaChange);
  }, []);

  return (
    <div style={{ display: "flex" }}>
      <DateRangePicker
        startDatePlaceholderText="Start date"
        endDatePlaceholderText="End date"
        showDefaultInputIcon
        orientation={isMobile ? "vertical" : "horizontal"}
        withFullScreenPortal={isMobile}
        startDate={startDate}
        startDateId="date-start-date"
        endDate={endDate}
        endDateId="date-end-date"
        onDatesChange={handleDatesChange}
        focusedInput={focusedInput}
        onFocusChange={(focusedInput) => setFocusedInput(focusedInput)}
        numberOfMonths={isMobile ? 12 : 2}
        verticalSpacing={0}
        autoFocus
        // 开启垂直滚动核心属性
        scrollable={isMobile}
        // 移动端限制日历容器高度,优化滚动体验
        calendarContainerStyle={isMobile ? { maxHeight: "70vh", overflowY: "auto" } : {}}
      />
    </div>
  );
}

export default DataPicker;

关键属性说明

  • scrollable={true}:开启日历垂直滚动功能,只有设置该属性为true时,orientation="vertical"才会触发滚动逻辑。
  • 媒体查询监听:通过useEffect绑定媒体查询的变化事件,确保响应式状态在窗口尺寸变化时实时更新。
  • calendarContainerStyle:给移动端日历设置最大高度,让日历在可视区域内独立滚动,避免影响页面整体滚动行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:12:03