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

React开发需求:实现点击切换月份的active类名,默认激活January

Toggle Active Month Class (Default January) Solution

Got it, let's get your month toggle functionality working properly! Here's a clean, scalable way to implement the active class switching, with January set as the default active month, using your existing Data[5].firstsixmonths array.

Full Working Component Code

import { useState } from 'react';

// Make sure your Data array is accessible in this component
const MonthSelector = () => {
  // Initialize active state to "January" for default activation
  const [activeMonth, setActiveMonth] = useState("January");

  // Handle click to update active month
  const handleMonthClick = (selectedMonth) => {
    setActiveMonth(selectedMonth);
  };

  return (
    <div className="first6-months">
      {Data[5].firstsixmonths.map((month, index) => (
        <p
          key={index}
          // Apply active class only when the month matches the active state
          className={`month-item ${month === activeMonth ? "active" : ""}`}
          onClick={() => handleMonthClick(month)}
        >
          {month}
        </p>
      ))}
    </div>
  );
};

export default MonthSelector;

Key Improvements & Explanations

  • State Tracking: We use React's useState hook to keep track of which month is active. Setting the initial state to "January" ensures it's active by default when the component loads.
  • Dynamic Class Logic: Instead of hardcoding class names like "jan" or "feb", we use a template literal to apply a base month-item class (for consistent styling across all months) plus the active class conditionally. This works for all 6 months, not just two.
  • Simplified Click Handler: Instead of passing the index key, we pass the actual month name to the click handler. This makes the code more readable and avoids issues if your array order ever changes.
  • Required Key Prop: Added the key prop to the mapped <p> element—React needs this to efficiently render lists and avoid warnings.

Styling Example

Don't forget to add CSS for the active class to make the state visible:

/* Base styles for all month items */
.month-item {
  padding: 0.5rem 1rem;
  margin: 0 0.25rem;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

/* Styles for the active month */
.month-item.active {
  background-color: #2563eb;
  color: white;
  font-weight: 500;
}

How It All Comes Together

  1. On first render, "January" is set as activeMonth, so it automatically gets the active class.
  2. When you click any month, handleMonthClick updates the state to that month.
  3. The component re-renders, and the newly selected month gets the active class while the previous one loses it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:44:06