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

React项目中Material UI的useStyles样式无法正常生效求助

问题原因

你的样式无法生效是两处命名/拼写不匹配导致的:

  • Product.jsx 中给内容容器绑定的类名是 classes.CardContent(首字母大写C),但 styles.js 中定义的对应样式 key 是 cardContent(首字母小写c),命名不一致导致样式无法关联。
  • Product.jsx 中给操作栏绑定的类名是 classes.CardActions,但 styles.js 中对应的 key 拼写错误,多写了一个字母r,写成了 carrdActions,同时首字母大小写不匹配,导致样式无法生效。

修正方案

统一类名命名和拼写即可:

1. 修正 Product.jsx 中的类名绑定

// 把原来的 classes.CardContent 改为 classes.cardContent
<div className={classes.cardContent}>
    <Typography variant="h5" gutterBottom>
        {product.name}
    </Typography>
    <Typography variant="h5">
        {product.price}
    </Typography>
</div>

// 把原来的 classes.CardActions 改为 classes.cardActions
<CardActions disableSpacing className={classes.cardActions}>
    <IconButton aria-label="Add to Cart">
        <AddShoppingCart/>
    </IconButton>
</CardActions>

2. 修正 styles.js 中的拼写错误

import { makeStyles } from "@material-ui/core";

export default makeStyles(() => ({
    root: {
        maxWidth: "100%"
    },
    media: {
        height: 0,
        paddingTop: '56.25%'
    },
    // 把原来的 carrdActions 改为正确拼写的 cardActions
    cardActions: {
        display: 'flex',
        justifyContent: 'flex-end'
    },
    cardContent: {
        display: 'flex',
        justifyContent: 'space-between'
    }
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:24:01