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

Material UI多选芯片组件绑定对象数组如何获取选中项ID

实现方案

你当前的代码是将选项的name作为选中值存储,无法直接获取对应id。最优解法是调整选中状态的存储逻辑,改为存储id数组,展示芯片时再通过id匹配对应的name渲染,既不影响前端展示效果,还能直接输出需要的id数组。

修改后的完整组件代码如下:

export const MultipleSelectChip = ({
  options,
  label,
  error,
  onRolesUpdate,
}: Props) => {
  const theme = useTheme();
  // 状态改为存储选中项的id数组,而非name数组
  const [selectedOptions, setSelectedOptions] = React.useState<string[]>([]);

  const handleChipChange = (
    event: SelectChangeEvent<typeof selectedOptions>,
  ) => {
    const {
      target: { value },
    } = event;
    const formattedValue = typeof value === 'string' ? value.split(',') : value;
    setSelectedOptions(formattedValue);
    // 直接将选中的id数组传递给父组件
    onRolesUpdate?.(formattedValue);
  };

  return (
    <div>
      <FormControl sx={{ m: 1, width: 300 }}>
        <InputLabel id="multiple-chip-label">{label}</InputLabel>
        <Select
          required
          labelId="multiple-chip-label"
          error={error}
          id="demo-multiple-chip"
          multiple
          value={selectedOptions}
          onChange={handleChipChange}
          input={<OutlinedInput id="select-multiple-chip" label={label} />}
          renderValue={(selectedIds) => (
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
              {selectedIds.map((id) => {
                // 通过id匹配对应的选项,取name展示在芯片上
                const matchedOption = options.find(opt => opt.id === id);
                return <Chip key={id} label={matchedOption?.name || ''} />;
              })}
            </Box>
          )}
          MenuProps={MenuProps}
        >
          {options.map((propOption) => (
            <MenuItem
              key={propOption.id}
              // MenuItem的value绑定id而非name
              value={propOption.id}
              style={getStyles(propOption, selectedOptions, theme)}
            >
              {propOption.name}
            </MenuItem>
          ))}
        </Select>
        <FormHelperText>Here's my helper text</FormHelperText>
      </FormControl>
    </div>
  );
};

核心改动说明

  • 状态存储逻辑调整:将原来存储name改为存储id,和最终需要输出的格式对齐
  • MenuItem绑定值调整:value属性从绑定name改为绑定id
  • 芯片展示逻辑调整:通过选中的id匹配对应选项的name渲染,展示效果和原来完全一致
  • 回调传值:状态更新后直接将id数组传递给父组件的onRolesUpdate方法
  • 注意同步调整getStyles方法的选中判断逻辑,将原来判断selectedOptions.includes(option.name)改为selectedOptions.includes(option.id)即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:39:03