在Material-UI中如何为:last-child元素设置:hover样式?
问题原因
你遇到的样式失效是因为 Material-UI 内置的MenuItem组件自带了:hover状态的默认样式,其CSS选择器优先级高于你当前嵌套在:last-child下的自定义hover样式,导致自定义样式被覆盖。
解决方法
方法1:提升自定义样式优先级(最小修改方案)
在MUI的makeStyles语法中,使用&&可以叠加当前类名,快速提升样式优先级,覆盖原生组件的默认样式:
const useStyles = makeStyles((theme) => ({ menu: { textDecoration: 'none', color: theme.palette.navy.default, cursor: 'pointer', fontWeight: 'bold', textTransform: 'uppercase', '&:last-child': { background: theme.palette.orange.default, borderRadius: '5em', color: theme.palette.white.default, // 用&&提升优先级,覆盖原生hover样式 '&&:hover': { background: theme.palette.green.default, }, }, }, }));
方法2:手动标记最后一项(更稳妥的方案)
不依赖CSS伪类选择器,直接在渲染时判断索引为最后一项的元素,单独绑定专用样式类,不受后续菜单结构调整(比如新增分隔线、装饰元素)影响,不会出现样式匹配错误的问题:
样式代码修改:
const useStyles = makeStyles((theme) => ({ menu: { textDecoration: 'none', color: theme.palette.navy.default, cursor: 'pointer', fontWeight: 'bold', textTransform: 'uppercase', }, // 单独定义最后一项的样式 lastMenuItem: { background: theme.palette.orange.default, borderRadius: '5em', color: theme.palette.white.default, '&:hover': { background: theme.palette.green.default, }, } }));
组件代码修改:
... const classes = useStyles(); <MenuList> {menu.map((item, index) => ( <MenuItem selected={false} key={index} className={`${classes.menu} ${index === menu.length - 1 ? classes.lastMenuItem : ''}`} > {item.title} </MenuItem> ))} </MenuList>
内容的提问来源于stack exchange,提问作者lemmusm
相关产品推荐
相关产品推荐

