简体   繁体   English

如何使用 React 和 Material UI 访问列表中所选项目的索引?

[英]How do I access the index of a selected item in list using React and Material UI?

I need to pass the index of the menu item selected onChange but don't know how to access it.我需要传递 onChange 所选菜单项的索引,但不知道如何访问它。

     const handleListChange = (e) => {
       console.log('Item Index: ', e.target.key);
     }


      <TextField
        select
        label="Select item"
        value={show}
        onFocus={getListArray}
        onChange={e => handleListChange(e)}
      >
        {listArray.map((value, index) =>
          <MenuItem
            key={index}
            value={value.title}
          >
            {value.title}
          </MenuItem>
        )}
      </TextField>

You can use map in order to get an array of titles and indexOf to get the index of the selected item.您可以使用map获取标题数组,使用indexOf获取所选项目的索引。

And here it is with ES6 and arrow syntax, which is even simpler:这里是 ES6 和箭头语法,更简单:

const handleListChange = (e) => {
  const index = listArray.map(item => item.title).indexOf(e.target.value);
  console.log(index);
}

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

相关问题 如何显示通过Material UI React选择了菜单列表中的哪个项目? - How do I show which item in the Menu List is selected with Material UI React? 如何从ReactJs和material UI中的下拉列表中获取所选项目的索引? - How to get the index of the selected item from a dropdown in ReactJs and material UI? 使用 React 时如何在 Material UI 中访问主题 object? - How do I access the theme object in Material UI when using React? 我如何在 React 中使用 Material UI 进行 Inset FAB? - How can i do Inset FAB using Material UI in React? 滚动到 material-ui 中的选定列表项 - Scroll to selected list item in material-ui 如何在React中自定义Material UI? - How do I customize Material UI in React? 当为 Material UI Autocomplete React 组件选择任何选项时,如何获得事件? - How do I get an event when any option is selected for a Material UI Autocomplete React component? 如何在React JS中的材料UI中的列表项上设置点击监听器 - How to set click listener on list item in material ui in react js 如何使用 React Material UI 的过渡组件动画将项目添加到列表? - How can I use React Material UI's transition components to animate adding an item to a list? 我如何在反应中使用材料 ui 库从我的自动完成框中获得选择 - How would i get the selected from my autocomplete box using material ui library in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM