![](/img/trans.png)
[英]JavaScript - How can I access the siblings of an event.currentTarget?
[英]MUI v5 - Can't access MenuItem attribute through event.currentTarget after update
我以前在 v4 上,我的 Select 和 MenuItems 設置如下:
const [select, setSelect] = useState('');
const [customName, setCustomName] = useState('');
const handleChange = (event) => {
setSelect(event.target.value);
setCustomName(event.currentTarget.getAttribute('name'));
};
...
<Select
label="Choose A Dataset"
onChange={handleChange}
value={select}
>
{tables &&
tables.map(
(table, index) =>
(
<MenuItem
key={table.name}
value={table.code}
name={table.name}
>
{table.name}
</MenuItem>
)
)}
</Select>
我可以通過訪問 menuItem 的 name 屬性
event.currentTarget.getAttribute('name');
但是,遷移到 v5 后,event.currentTarget 返回 null。 有什么建議么?
SelectInput
有這個onChange
定義:
onChange?: (event: SelectChangeEvent<T>, child: React.ReactNode) => void;
這意味着您可以讓孩子點擊作為您的handleChange
的第二個參數。 在這里,您可以使用child.props.name
訪問 name 屬性。
但是值得注意的是MenuItem
沒有 name 屬性,如果您定義它 Typescript 將突出顯示為錯誤。 為避免這種情況,您可以使用event.target.value
查找具有匹配code
的表並以這種方式獲取名稱:
const name = tables.find((table) => table.code === event.target.value).name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.