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

React日历开发:如何在应用首次加载时显示当前日期

How to Auto-Scroll to Current Date on Initial Load for Your React Calendar Component

Hey there! Let's get your calendar to automatically jump to today's date when it first loads. Here's a step-by-step solution tailored to your existing code:

Step 1: Add Unique Identifiers to Each Date Element

First, we need a way to locate the element corresponding to today's date. Let's modify your RenderDates component to add a data-date attribute to each <Date> element, using the ISO format (YYYY-MM-DD) for easy matching:

import moment from 'moment';
// Don't forget to import your Date and ContentDate components

export default function RenderDates(props) { 
  const dates_ = []; 
  const startDate = moment('12-29-2019', 'MM-DD-YYYY'); 
  let currentDate = startDate.clone(); // Clone to avoid mutating the original moment object

  for(let i = 1; i <= 53*7; i++) {
    currentDate.add(1, 'days'); // Increment date first to match your original logic
    const dateString = currentDate.format('YYYY-MM-DD');
    
    dates_.push( 
      <Date key={dateString} data-date={dateString}> 
        <ContentDate> 
          <ShortDate>{moment.weekdaysShort()[i%7]}</ShortDate> 
          <span>{currentDate.get('Date')}</span> 
        </ContentDate> 
      </Date> 
    ) 
  } 
  return dates_; 
}

Step 2: Add Scroll Logic in the Parent Component

Next, we'll use React's useRef and useEffect hooks to handle the auto-scroll once the component mounts. Wrap your RenderDates component in a scrollable container, then target today's date element:

import { useRef, useEffect } from 'react';
import moment from 'moment';
import RenderDates from './RenderDates';

function Calendar() {
  const calendarContainerRef = useRef(null);

  useEffect(() => {
    // Get today's date in ISO format
    const today = moment().format('YYYY-MM-DD');
    
    // Find the element matching today's date
    const targetDateElement = calendarContainerRef.current?.querySelector(`[data-date="${today}"]`);

    if (targetDateElement) {
      // Smoothly scroll to the target date, centered in the viewport
      targetDateElement.scrollIntoView({
        behavior: 'smooth',
        inline: 'center', // Use 'start' if you want it aligned to the left
        block: 'nearest'
      });
    } else {
      // If today is outside your calendar's range, scroll to the start (adjust to end if preferred)
      calendarContainerRef.current.scrollLeft = 0;
      console.log("Today's date is outside the calendar's date range");
    }
  }, []); // Empty dependency array ensures this runs only on initial mount

  return (
    <div 
      ref={calendarContainerRef}
      style={{ 
        overflowX: 'auto', 
        whiteSpace: 'nowrap',
        // Add any additional styling for your container
      }}
    >
      <RenderDates />
    </div>
  );
}

export default Calendar;

Key Notes:

  • Moment Object Immutability: We use .clone() on the startDate to avoid mutating the original moment object, which could cause unexpected date calculations down the line.
  • Customizable Scroll Behavior: The scrollIntoView options let you tweak how the date is positioned—inline: 'center' centers the date in the scrollable container, while behavior: 'smooth' adds a polished animated scroll (swap to 'auto' for instant scrolling if you prefer).
  • Edge Case Handling: We added a fallback for when today's date falls outside your 2019-12-30 to 2021-03-01 range, so the calendar doesn't break and instead defaults to scrolling to the start.

That should do it! Your calendar will now automatically scroll to today's date when the app first loads.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:57:38