gpt4 book ai didi

reactjs - 获取MenuItem Material ui的值

转载 作者:行者123 更新时间:2023-12-03 13:28:09 27 4
gpt4 key购买 nike

我正在使用Material UI对于菜单和菜单项。我试图获取菜单项的值,但它不起作用。

这是我的代码:

<Menu value= { this.state.selectedItem }>
<MenuItem onClick={this.listClicked}
leftIcon={
<FontIcon
className="material-icons"
style={{ color: 'white', margin: '0' }}>
format_list_bulleted
</FontIcon>
}
/>
<MenuItem onClick={this.settingClicked}
leftIcon={
<FontIcon
className="material-icons"
style={{ color: 'white', margin: '0' }}>
settings
</FontIcon>
}
/>
</Menu>

public listClicked = (value) => {
this.setState({
selectedItem :value
})
console.log(this.state.selectedItem)
}

我没有得到该值,并且在导航器的控制台中我有一个对象。

你能帮我吗?

谢谢

最佳答案

使用 data-attribute菜单项上并从单击事件的 currentTarget 访问它。请注意,data-my-value 属性在 event.currentTarget.dataset 上变为 myValue

const handleClick = event => {
const { myValue } = event.currentTarget.dataset;
console.log(myValue) // --> 123
}

<MenuItem
data-my-value={123}
onClick={handleClick}
>
<div>text</div>
</MenuItem>

为什么使用currentTarget而不是targetcurrentTarget 指的是事件监听器直接附加到的元素,而 target 指的是 MenuItem 中的特定元素,例如某些 div ,即被点击。该 div 没有 data-my-value 属性,因此 targetdataset< 上不会有 myValue/。因此,在这种情况下请使用 currentTarget

相关:How to access custom attributes from event object in React?

关于reactjs - 获取MenuItem Material ui的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com