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

如何在React中向CSS模块传递Props?NextJS代码问题排查

问题分析与修复方案

你的代码存在三个核心问题:

1. Props传递与访问不匹配

你给Hero组件传的heroHeight是字符串值('height: 400px'),但在组件里却尝试访问heroHeight.updateTheHeight——字符串没有这个属性,直接导致报错。

2. CSS模块的使用逻辑错误

CSS模块是编译时生成的静态类,无法在运行时把动态样式值注入到预定义的.updateTheHeight类中。你想通过类接收动态高度的思路不成立。

3. 模板字符串语法错误

className={${styles.pageWidth} ${style[heroHeight.updateTheHeight]} 缺少闭合的},语法不合法。


修复方案

如果要实现动态高度,推荐两种简单可行的方式:

方式一:直接使用内联样式

把高度值作为单独的props传递,结合内联样式实现动态控制:

/about/page.js

<Hero heroHeight="400px" />

Hero.js

'use client';

import styles from '../page.module.css';
import heroStyles from './Hero.module.css';

const Hero = ({ heroHeight }) => {
  return (
    <div 
      className={`${styles.pageWidth} ${heroStyles.updateTheHeight}`}
      style={{ height: heroHeight }}
    >
    </div>
  );
};

export default Hero;

Hero.module.css

.updateTheHeight{
  border: 1px solid green;
}

方式二:通过CSS变量传递动态值

如果想保留CSS模块的写法,可以用CSS变量实现动态注入:

/about/page.js

<Hero heroHeight="400px" />

Hero.js

'use client';

import styles from '../page.module.css';
import heroStyles from './Hero.module.css';

const Hero = ({ heroHeight }) => {
  return (
    <div 
      className={`${styles.pageWidth} ${heroStyles.updateTheHeight}`}
      style={{ '--hero-height': heroHeight }}
    >
    </div>
  );
};

export default Hero;

Hero.module.css

.updateTheHeight{
  border: 1px solid green;
  height: var(--hero-height);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:52:09