var*_*ika 0 reactjs material-ui
我是 Material-ui 和 React 的新手,我需要在循环中动态创建多个菜单。请找到代码片段:
state = {
anchorEl: null,
};
handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { anchorEl } = this.state;
let items = _.map(results, (item, index) => {
return (
<ListItem
key={item.ID}
divider
>
<ListItemSecondaryAction>
<IconButton
aria-label="More"
aria-owns={anchorEl ? 'long-menu' : null}
aria-haspopup="true"
onClick={this.handleClick}
>
<MoreVertIcon />
</IconButton>
<Menu
id="long-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
PaperProps={{
style: {
maxHeight: 200,
width: 200,
},
}}
>
<MenuItem>
<IconButton onClick={() => this.props.delete(item.ID)} >
Delete entry<DeleteIcon />
</IconButton>
</MenuItem>
</Menu>
<ListItemSecondaryAction>
</ListItem>
)
})
return (
<Fragment>
<List>
{items}
</List>
</Fragment>
)
}
Run Code Online (Sandbox Code Playgroud)
现在,使用上面的代码,菜单可以正常工作并且用户界面也很好。但每当我尝试通过单击菜单内的“删除”图标来删除条目时,总是会删除最后一个条目,即 item.ID 传递最后一个元素的值,并且最后一个条目被删除。有没有一种方法可以为每个条目创建唯一的菜单项并以确保删除正确的项目而不是最后一个项目的方式管理状态。注意:“结果”是动态加载的任何列表,“删除”函数实现删除相应条目的功能
提前致谢。
我建议使用另一个子组件来呈现您的列表项。在您当前的示例中,您只有一个anchorEl,这意味着无论您单击何处,始终会打开一个菜单并执行该操作,这是最后一个菜单。如果您有菜单项的子组件,则每个组件将有自己的状态并且仅适用于该项目。
class Main extends Component {
render() {
let items = _.map(results, (item, index) => {
return (
<MenuItemComponent key={item.ID} item={item} onClick={this.handleClick} onDelete={(item) => this.props.delete(item.ID)} />
)
})
return (
<Fragment>
<List>
{items}
</List>
</Fragment>
)
}
}
class MenuItemComponent extends Component {
state = {
anchorEl: null,
};
handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { item } = this.props;
const { anchorEl } = this.state;
return (
<ListItem
divider
>
<ListItemSecondaryAction>
<IconButton
aria-label="More"
aria-owns={anchorEl ? 'long-menu' : null}
aria-haspopup="true"
onClick={this.handleClick.bind(this)}
>
<MoreVertIcon />
</IconButton>
<Menu
id="long-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose.bind(this)}
PaperProps={{
style: {
maxHeight: 200,
width: 200,
},
}}
>
<MenuItem>
<IconButton onClick={() => this.props.onDelete(item)} >
Delete entry<DeleteIcon />
</IconButton>
</MenuItem>
</Menu>
</ListItemSecondaryAction>
</ListItem>
)
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例https://codesandbox.io/s/nn555l48xm
| 归档时间: |
|
| 查看次数: |
5827 次 |
| 最近记录: |