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

如何在MUI styled的ListItem hover时定位内部ListButton组件?

解决MUI Drawer中ListItem hover时修改内部ListItemButton样式的问题

要实现TheListItem hover时修改内部定制ListButton的样式,你可以利用MUI styled(从@mui/material/styles导入)的嵌套选择器特性,通过$符号引用子组件的类名来实现样式关联。

完整代码示例

import { Drawer, ListItem, ListItemButton } from '@mui/material';
import { styled } from '@mui/material/styles';

// 先定义定制的ListButton
const ListButton = styled(ListItemButton)(({ theme }) => ({
  borderRadius: theme.shape.borderRadius,
  transition: 'all 0.2s ease',
  padding: theme.spacing(1, 2),
}));

// 定义TheListItem,通过嵌套选择器实现hover时修改子组件样式
const TheListItem = styled(ListItem)(({ theme }) => ({
  padding: theme.spacing(0.5),
  // 核心:父元素hover时,选中内部的ListButton并修改样式
  '&:hover $ListButton': {
    backgroundColor: theme.palette.grey[100],
    color: theme.palette.primary.main,
    fontWeight: 500,
  },
}));

// 使用组件
export default function CustomDrawer() {
  return (
    <Drawer open={true} variant="permanent">
      <TheListItem>
        <ListButton>
          首页
        </ListButton>
      </TheListItem>
      <TheListItem>
        <ListButton>
          我的订单
        </ListButton>
      </TheListItem>
    </Drawer>
  );
}

关键要点

  • 顺序很重要:必须先定义ListButton,再定义TheListItem,这样TheListItem的styled配置才能通过$ListButton正确引用子组件的类名。
  • 嵌套选择器语法:&:hover $ListButton表示当TheListItem处于hover状态时,选中内部的ListButton组件并应用样式,这是MUI styled支持的类名引用方式,无需硬编码类名。
  • 样式过渡:给ListButton添加过渡效果,能让hover状态的样式变化更平滑,提升用户体验。

排查注意事项

  1. 如果样式仍不生效,检查子组件是否被其他更高优先级的样式覆盖,可以通过浏览器开发者工具查看元素的样式优先级,调整样式的权重(比如增加具体的属性选择器,或避免子组件使用!important)。
  2. 确认没有误用选择器:比如不要写成$ListButton:hover,这表示子组件自身hover时的样式,而非父组件hover时影响子组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:15:34