我正在尝试使用 Material UI 根据下拉选择更改状态。
问题是下面的代码(精简)返回列表项,所以我不知道下一步该做什么。
从 handleClose 方法中的 console.log(event.target) 返回
<li tabindex="0" class="MuiButtonBase-root-23 MuiListItem-root-72 MuiListItem-default-75 MuiListItem-gutters-79 MuiListItem-button-80 MuiMenuItem-root-70" role="menuitem">
精简组件:
事件从 API 调用中获取。感谢您的任何想法。
import React, { Component } from "react";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
class ABC extends Component {
constructor(props) {
super(props);
this.state = {
campaigns: [],
anchorEl: null
};
this.handleClick = this.handleClick.bind(this);
this.handleClose = this.handleClose.bind(this);
}
// For the dropdown
handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = event => {
this.setState({ anchorEl: null });
console.log(event.target);
};
render() {
const { campaigns, anchorEl } = this.state;
return (
<div>
<Button
aria-owns={anchorEl ? "simple-menu" : null}
aria-haspopup="true"
onClick={this.handleClick}
>
CHOOSE CAMPAIGN
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
>
{campaigns.map(item => (
<MenuItem key={item.Id} onClick={event => this.handleClose(event)}>
{item.Name}
</MenuItem>
))}
</Menu>
{JSON.stringify(this.state.value)}
</div>
);
}
}
最佳答案
将 MenuItem 更新为:
<MenuItem key={item.Id} onClick={(event) => this.handleClose(item, event)}>{item.Name}</MenuItem>
通过这种方式,您将获得该特定项目作为事件处理程序的参数。我还注意到相同的函数作为菜单组件的 onClose 处理程序传递,这看起来很困惑。如果 Menu 使用不同的参数触发 onClose 事件,这可能会导致问题。
关于javascript - 来自 React Material UI MenuItem 单击事件的 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51274125/