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
useStatehook 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-itemclass (for consistent styling across all months) plus theactiveclass 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
keyprop 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
- On first render, "January" is set as
activeMonth, so it automatically gets theactiveclass. - When you click any month,
handleMonthClickupdates the state to that month. - The component re-renders, and the newly selected month gets the
activeclass while the previous one loses it.
内容的提问来源于stack exchange,提问作者Nikhil Soni
相关产品推荐
相关产品推荐

