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

React中如何结合state给className赋值?CSS Module滚动切换类名报错如何解决

问题原因

你代码的错误出在动态读取CSS Module类名的语法错误:
classes.this.state.name的写法会被JS解析为「访问classes对象下的this属性,再访问这个this属性的state属性」,但classes对象根本没有this属性,所以触发Cannot read properties of undefined (reading 'state')报错。

解决方法

JS中读取对象的动态属性需要使用方括号语法,将你的className写法改成以下即可:

<div className={classes[this.state.name]}>

额外优化建议

  • 组件卸载时需要移除滚动事件监听,避免内存泄漏,添加对应生命周期函数即可
  • 滚动事件触发频率极高,可以添加节流逻辑减少不必要的state更新,优化性能

修正后的完整代码

import React ,{Component} from 'react';
import classes from './Toolbar.css';

class Toolbar extends Component{
    state={
        name:'Toolbar'
    }

    listenScrollEvent = e => {
        console.log(window.scrollY);
        if (window.scrollY > 200) {
          this.setState({name: 'Toolbarnew'})
        } else if(window.scrollY < 200) {
          this.setState({name: 'Toolbar'})
        }
    }

    componentDidMount() {
        window.addEventListener('scroll', this.listenScrollEvent)
    }

    componentWillUnmount() {
        window.removeEventListener('scroll', this.listenScrollEvent)
    }

    render(){
        return(
            <div className={classes[this.state.name]}>
                {this.props.children}
            </div>    
        )
    }
}

export default Toolbar;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:06:03