最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I access the index of a selected item in list using React and Material UI? - Stack Overflow

programmeradmin2浏览0评论

I need to pass the index of the menu item selected onChange but don't know how to access it.

     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>

I need to pass the index of the menu item selected onChange but don't know how to access it.

     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>
Share Improve this question asked Jul 16, 2021 at 0:53 sbadensbaden 5653 gold badges16 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You can use map in order to get an array of titles and indexOf to get the index of the selected item.

And here it is with ES6 and arrow syntax, which is even simpler:

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

评论列表(0)

  1. 暂无评论