簡體   English   中英

如何使用 React 和 Material UI 訪問列表中所選項目的索引?

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

我需要傳遞 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>

您可以使用map獲取標題數組,使用indexOf獲取所選項目的索引。

這里是 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM