React组件无法读取CSS模块类,报错Cannot read property 'dropdown' of undefined求助
Let's break down what's going wrong here and fix it step by step:
1. The Root Issue: Incorrect CSS Module Import
Your error Cannot read property 'dropdown' of undefined means the classes variable you're trying to use is actually undefined. This happens because you're using the wrong import syntax for CSS modules.
CSS modules export a single object (with mapped class names) as the default export, not a named export called classes. Your current code is trying to destructure a non-existent named export.
Fix the Import Statement
Replace this:
import { classes } from './DropdownMenu.module.css';
With this:
import classes from './DropdownMenu.module.css';
2. Verify Class Name References
Once you fix the import, both of these class name reference styles will work perfectly:
- Dot notation:
classes.dropdown - Bracket notation:
classes["dropdown"]
Here's your corrected full component code:
import classes from './DropdownMenu.module.css'; function DropdownMenu() { return( <div className={classes.dropdown}> {/* 组件内容 */} </div> ) } export default DropdownMenu;
3. Extra Checks If the Problem Persists
If you still run into issues after fixing the import, try these quick troubleshooting steps:
- Confirm CSS module support: If you're using Create React App, CSS modules are enabled by default for files ending with
.module.css. If you have a custom Webpack setup, ensurecss-loaderhasmodules: trueconfigured. - Check file naming: Double-check that your CSS file is named exactly
DropdownMenu.module.css(case matters on Linux/macOS systems). - Restart your dev server: Sometimes changes to imports or dependency setups require a fresh start of
npm startto take effect.
内容的提问来源于stack exchange,提问作者GettingStarted

