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

MUI ListItem点击冲突及ListItemButton样式异常问题咨询

MUI ListItem点击secondaryAction触发父组件onClick的解决办法

方案1:阻止事件冒泡(最快解决,保留原有样式)

直接在IconButton的点击事件里阻止事件向上冒泡,就能让右侧按钮的点击行为独立,完全保留原来的列表项样式:

<ListItem
  button
  secondaryAction={
    <IconButton
      edge='end'
      aria-label='more'
      onClick={(e) => {
        e.stopPropagation(); // 终止事件冒泡,避免触发ListItem的onClick
        console.log('hello');
      }}
    >
      <MoreHorizIcon />
    </IconButton>
  }
  onClick={handleClick}
>
  <ListItemIcon>
    {!isFolderOpen ? (
      <FolderIcon sx={{ color: theme => theme.palette.primary.main }} />
    ) : (
      <FolderOpenIcon sx={{ color: theme => theme.palette.primary.main }} />
    )}
  </ListItemIcon>
  <ListItemText primary={name && name} />
</ListItem>

原理:DOM事件默认会向上冒泡到父元素,调用e.stopPropagation()可以切断这个传递路径,让ListItem接收不到按钮的点击事件。

方案2:正确使用ListItemButton并修复hover样式

如果想采用ListItemButton的结构,只需调整ListItem的内边距,让按钮占满整个列表项,就能让hover效果恢复成整体:

<ListItem
  disablePadding // 禁用ListItem默认内边距,让ListItemButton填满整个列表项
  secondaryAction={
    <IconButton
      edge='end'
      aria-label='more'
      onClick={() => console.log('hello')}
    >
      <MoreHorizIcon />
    </IconButton>
  }
>
  <ListItemButton onClick={handleClick}>
    <ListItemIcon>
      {!isFolderOpen ? (
        <FolderIcon sx={{ color: theme => theme.palette.primary.main }} />
      ) : (
        <FolderOpenIcon sx={{ color: theme => theme.palette.primary.main }} />
      )}
    </ListItemIcon>
    <ListItemText primary={name && name} />
  </ListItemButton>
</ListItem>

原理:原来的hover样式分裂,是因为ListItem默认的内边距导致ListItemButton无法填满整个列表项。用disablePadding去掉内边距后,按钮会自动占据剩余空间,hover效果就和原生ListItem button的表现一致了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:45:41