admin管理员组

文章数量:1410717

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);
}

本文标签: javascriptHow do I access the index of a selected item in list using React and Material UIStack Overflow