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

Mantine React Combobox如何获取选项的Key值(Item ID)

解决Mantine Combobox在onOptionSubmit中获取item ID的问题

给你几个优雅的实现方案,按需选择:

方案一:将item ID设为Option的value(最直接)

既然需要拿到ID,不如直接把Combobox.Option的value设为item的ID,在Option内部正常显示label即可。onOptionSubmit回调会直接返回这个ID,之后你可以根据ID从数据源中找到对应的label或其他信息:

const listOptions = filteredOptions.map((item) => (
  <Combobox.Option value={item.id} key={item.id}>
    {item.label}
  </Combobox.Option>
));

return (
  <Combobox
    onOptionSubmit={(selectedId) => {
      const selectedItem = filteredOptions.find(item => item.id === selectedId);
      console.log('选中的ID:', selectedId);
      console.log('选中的label:', selectedItem?.label);
    }}
  >
    {/* 补充Combobox的必要组件,如Combobox.Input、Combobox.Dropdown等 */}
    {listOptions}
  </Combobox>
);

方案二:用自定义data属性存储ID

如果必须保留value为label,可以给Combobox.Option添加自定义data-*属性存储ID,再在onOptionSubmit中通过事件对象获取:

const listOptions = filteredOptions.map((item) => (
  <Combobox.Option 
    value={item.label} 
    key={item.id}
    data-item-id={item.id}
  >
    {item.label}
  </Combobox.Option>
));

return (
  <Combobox
    onOptionSubmit={(value, event) => {
      // 定位到对应Option元素,提取存储的ID
      const optionElement = event.target.closest('[data-item-id]');
      const itemId = optionElement?.dataset.itemId;
      console.log('选中的label:', value);
      console.log('选中的ID:', itemId);
    }}
  >
    {/* 补充必要组件 */}
    {listOptions}
  </Combobox>
);

方案三:利用useCombobox钩子(更灵活)

如果愿意改用钩子式写法,useCombobox的onSelect回调可以直接拿到选中选项的完整props,能更便捷地获取ID:

import { useCombobox } from '@mantine/core';

const combobox = useCombobox({
  onSelect: ({ option }) => {
    // option包含你给Combobox.Option传入的所有props,直接取id即可
    console.log('选中的ID:', option.id);
    console.log('选中的label:', option.value);
  },
});

const listOptions = filteredOptions.map((item) => (
  <Combobox.Option 
    value={item.label} 
    key={item.id}
    id={item.id}
    {...combobox.getOptionProps()}
  >
    {item.label}
  </Combobox.Option>
));

return (
  <Combobox {...combobox.getComboboxProps()}>
    <Combobox.Input {...combobox.getInputProps()} />
    <Combobox.Dropdown {...combobox.getDropdownProps()}>
      {listOptions}
    </Combobox.Dropdown>
  </Combobox>
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:55:11