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

Material UI下拉选择菜单无法获取子菜单项值求助

解决Material UI Select分类菜单子项选中异常问题

问题原因

你当前的实现把子MenuItem嵌套在了父MenuItem内部,这违反了Material UI Select组件的结构规范:Select的选项必须是直接的MenuItem子元素。嵌套情况下,点击子MenuItem时会触发父MenuItem的选中事件(事件冒泡),同时父MenuItem自身设置了value属性,会被识别为可选中选项,最终导致选中父菜单的值而非子项。

解决方案

方案1:父分类仅作为分组标题(不可选中)

使用ListSubheader作为分组标题,子MenuItem作为Select的直接子元素,结构上保持平级:

import { ListSubheader } from '@mui/material';

// 修正后的Select组件
<Select
  displayEmpty
  defaultValue=""
  value={search}
  onChange={handleChange}
  id="grouped-select"
  input={<OutlinedInput />}
  label="Category"
  size="small"
  sx={{
    width: "160px",
    height: "100%",
    borderRadius: 0,
    textTransform: "uppercase"
  }}
  renderValue={(selected) => {
    if (!selected) {
      return <Typography variant="subtitle2">Select Category</Typography>;
    }
    return <Typography variant="subtitle2">{selected}</Typography>;
  }}
>
  <MenuItem value="">
    <Typography variant="subtitle2">Select Category</Typography>
  </MenuItem>

  {/* 婴儿产品分组 */}
  <ListSubheader sx={{ textTransform: 'uppercase' }}>Baby Products</ListSubheader>
  {babyProducts.map((item) => (
    <MenuItem
      key={item}
      sx={{ lineHeight: "12px", pl: 4 }} // 缩进区分子项
      value={item}
    >
      <Typography variant="subtitle2">{item}</Typography>
    </MenuItem>
  ))}

  {/* 巧克力分组(同理) */}
  <ListSubheader sx={{ textTransform: 'uppercase' }}>Chocolates</ListSubheader>
  {chocolates.map((item) => (
    <MenuItem
      key={item}
      sx={{ lineHeight: "12px", pl: 4 }}
      value={item}
    >
      <Typography variant="subtitle2">{item}</Typography>
    </MenuItem>
  ))}
</Select>

方案2:父分类和子项都可选中

如果需要父分类本身也作为可选选项,将父MenuItem和子MenuItem放在同一层级,通过样式区分层级:

<Select
  // 其他属性保持不变
>
  <MenuItem value="">
    <Typography variant="subtitle2">Select Category</Typography>
  </MenuItem>

  {/* 父分类选项 */}
  <MenuItem key="Baby Products" value="Baby Products">
    <Typography variant="subtitle2">Baby Products</Typography>
  </MenuItem>
  {/* 子项选项,缩进显示 */}
  {babyProducts.map((item) => (
    <MenuItem
      key={item}
      sx={{ lineHeight: "12px", pl: 4 }}
      value={item}
    >
      <Typography variant="subtitle2">{item}</Typography>
    </MenuItem>
  ))}

  {/* 巧克力分类同理 */}
  <MenuItem key="Chocolates" value="Chocolates">
    <Typography variant="subtitle2">Chocolates</Typography>
  </MenuItem>
  {chocolates.map((item) => (
    <MenuItem
      key={item}
      sx={{ lineHeight: "12px", pl: 4 }}
      value={item}
    >
      <Typography variant="subtitle2">{item}</Typography>
    </MenuItem>
  ))}
</Select>

关键修改点

  • 移除MenuItem的嵌套结构,所有可选的MenuItem必须是Select的直接子元素
  • 用ListSubheader或样式缩进区分分组层级,避免事件冒泡导致的选中异常
  • 确保每个MenuItem的value唯一且正确对应选项内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:37:34