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

React CSS Modules中遍历数组绑定className无效的问题咨询

How to Access CSS Modules Class Names from a Menu Items Array

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:12:45