[英]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.