如何在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
相关产品推荐
相关产品推荐

