React CSS Modules中遍历数组绑定className无效的问题咨询
Got it, let's fix this CSS Modules issue for your navigation menu. The core problem here is that when you use item.cName directly, you’re passing the raw string (like 'navLinks') as the class name—but CSS Modules transforms your original class names into unique, hashed values (e.g., MainNavigation_navLinks_xyz123) that live in the imported style object. Your current approach isn’t accessing that transformed value.
Solution: Use Bracket Notation to Fetch the Hashed Class Name
Instead of passing item.cName straight to the className prop, use it as a key to look up the correct transformed class name from the style object. Here’s how to update your code:
import style from "./MainNavigation.module.css"; {MenuItems.map((item, index) => { return ( <li key={index}> {/* Use style[item.cName] to get the hashed class name */} <a className={style[item.cName]} href={item.url}> {item.title} </a> </li> ); })}
Why This Works
CSS Modules exports an object where each key matches the original class name from your .module.css file, and the value is the globally unique, hashed class name that gets applied to your DOM elements. Bracket notation (style[item.cName]) lets you dynamically access the correct hashed value using the string stored in your MenuItems array.
Just make sure your MainNavigation.module.css includes the class you’re referencing:
/* MainNavigation.module.css */ .navLinks { /* Your navigation link styles here */ padding: 0.5rem 1rem; text-decoration: none; color: #2d3748; }
Bonus: Handling Multiple Class Names
If you ever need to apply multiple CSS Module classes (e.g., if item.cName was 'navLinks navLinks--active'), split the string and map over each class to fetch its hashed version:
className={item.cName.split(' ').map(cls => style[cls]).join(' ')}
内容的提问来源于stack exchange,提问作者brendan

