简体   繁体   English

如何从 MUI 中的多 select 中获取选定的复选框值和 id

[英]How to get selected checkbox value and id from the multi select in MUI

I am using MUI select component with multi-select.我正在使用具有多选功能的 MUI select 组件。 The multi-select rendering uses the below JSON array.多选渲染使用下面的 JSON 数组。 Is there any way we can get both the selected item id and value?有什么方法可以同时获取所选项目的 ID 和值?

Here is the code sandbox URL: https://codesandbox.io/s/cranky-currying-ce8djy?file=/src/App.js这里是代码沙箱URL: https://codesandbox.io/s/cranky-currying-ce8djy?file=/src/App.js

JSON Array: const menuItems = [
  { id: "8271e42a-8982-44b8-9745-3271e0cf9d12", value: "Item 1" },
  { id: "c0f3e462-02f8-4d8d-ae05-6965b7902a80", value: "Item 2" },
  { id: "c0f3dfyh-02f8-4d8d-ae05-6965b7dw3456", value: "Item 3" }
];



 export default function App() {
  const [selected, setSelected] = useState([]);

  const handleChange = (event) => {
    const {
      target: { value }
    } = event;
    setSelected(typeof value === "string" ? value.split(",") : value);
    console.log(selected);
  };

  const ITEM_HEIGHT = 48;
  const ITEM_PADDING_TOP = 8;

  const lteProps = {
    PaperProps: {
      style: {
        maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
        width: 250
      }
    }
  };
  return (
    <div className="App">
      <FormControl fullWidth={true}>
        <Select
          multiple
          value={selected}
          onChange={handleChange}
          renderValue={(selected) => selected.join(", ")}
          MenuProps={lteProps}
        >
          {menuItems.map((item) => (
            <MenuItem key={item.id} value={item.value}>
              <Checkbox checked={selected.indexOf(item.value) > -1} />
              <ListItemText primary={item.value} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

Appreciate any help.感谢任何帮助。

I worked before on MUI.我以前在 MUI 工作过。
You need to add one more parameter to the handleChange function to access ID.您需要在handleChange function 中再添加一个参数来访问 ID。 But it is currently returning ID with .$ .但它目前正在返回带有.$的 ID。 So you have to filter these two chars.所以你必须过滤这两个字符。

  const handleChange = (event,obj) => {
    const {
      target: { value }
    } = event;
    setSelected(typeof value === "string" ? value.split(",") : value);
    // on selecting first option, will return
    // .$8271e42a-8982-44b8-9745-3271e0cf9d12
    console.log(obj.key);
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM