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

Next.js中如何通过props传递CSS modules 向子组件传递className

Next.js 11.1.0 父传子传递CSS Modules 样式未定义报错解决

报错核心原因

component2中h2样式未定义报错,通常为以下两种情况:

  • 你的./css/styles.module.css文件中没有定义.h2类名,CSS Modules只会导出文件中明确声明的类,未声明的类访问结果为undefined
  • 组件命名不规范:React组件要求使用大驼峰命名,你代码中component1、component2使用小驼峰命名,可能引发组件渲染异常连带样式加载失败

修正后代码

第一步:先确保styles.module.css存在对应类

/* ./css/styles.module.css */
.h1 {
  /* 你的h1自定义样式 */
  font-size: 28px;
}
.h2 {
  /* 你的h2自定义样式,必须显式声明 */
  font-size: 22px;
  color: #333;
}

第二步:原传递styles对象方案可用代码

Component1 代码

import React from 'react'
import Component2 from './Component2'
import styles from './css/styles.module.css'

// 组件名改大驼峰符合React规范
function Component1() {
    return (
        <>
            <h1 className={styles.h1}>hello World</h1>
            <Component2 styles={styles}/>
        </>
    )
}

export default Component1

Component2 代码

import React from 'react'

// 组件名改大驼峰符合React规范
function Component2(props) {
    // 加空值兜底,避免未传props时报错
    const styles = props.styles ?? {}
    return (
        <>
            <h2 className={styles.h2}>Hello World 2</h2>
        </>
    )
}

export default Component2

更推荐的低耦合写法

不需要传递整个styles对象,直接父组件传递对应className即可,子组件复用性更强:

调整后Component1代码

import React from 'react'
import Component2 from './Component2'
import styles from './css/styles.module.css'

function Component1() {
    return (
        <>
            <h1 className={styles.h1}>hello World</h1>
            <Component2 h2Class={styles.h2}/>
        </>
    )
}

export default Component1

调整后Component2代码

import React from 'react'

function Component2(props) {
    return (
        <>
            <h2 className={props.h2Class}>Hello World 2</h2>
        </>
    )
}

export default Component2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:51:00