gpt4 book ai didi

reactjs - React + Material UI 中的子菜单无法正确关闭

转载 作者:行者123 更新时间:2023-12-03 14:24:56 25 4
gpt4 key购买 nike

我有一个嵌套菜单结构,如下所示:

 menuItems = [
{
"key": "key1",
"caption": "Text1"
},
{
"key": "key2",
"caption": "Text2",
"subMenuItems": [
{
"key": "key3",
"caption": "Text3",
"subMenuItems": [
{
"key": "key4",
"caption": "Text4"
}
]
},
{
"key": "key5",
"caption": "Text5",
"subMenuItems": []
},
{
"key": "key6",
"caption": "Text6"
}
]
},
{
"key": "key7",
"caption": "Text7"
}
]

我想在打开到其父级右侧的子菜单中打开子菜单项。类似Angular Material Menu (Nested menu example)的东西.

我尝试使用 Material UI 菜单,它根据需要打开菜单 ( See here ),但有以下 2 个问题:

  1. 如果您先打开父菜单,然后再打开任何子菜单,则需要在菜单外部单击多次。相反,它应该在单击外部时关闭所有父+子菜单。
  2. 如果您想通过单击另一个父菜单项来切换子菜单,则需要先单击父菜单(或按照问题 1,单击外部)以关闭当前打开的子菜单,然后单击所需的父菜单项以打开相应的子菜单。

问题 1 可以使用 ClickAwayListener 解决如implemented here ,但即使尝试切换到另一个子菜单(例如从“按钮 3”子菜单切换到“更多项目”),它也会关闭所有菜单。

谢谢。

最佳答案

让我们构建一个抽屉/导航栏,它接收项目对象列表并以递归方式渲染。首先,像您在 menuItems 中所做的那样定义结构。 ,我会稍微改变一下:

const items = [
{name: 'Shallow Item', path='/', type:'shallow'},
{
name: 'Nested',
type: 'nested',
items:[
{name: 'Shallow again', path='/nestedpath'}
]
}
]

现在您的列表中有两个项目,一个是普通的浅项目,不包含嵌套选项,第二个是嵌套项目,其中包含浅项目列表。

现在我们必须构建或两个核心组件:<NestedItem><ShallowItem> 。它们应该看起来像这样:

const ShallowItem = ({item, onClick}) =>(
<ListItem
component={Link}
to={item.path || #}
onClick={onClick ? onClick : ()=>{} }
>
<ListItemText primary={item.name}/>
{Boolean(nested) &&
<Icon>
{collapsed ? 'arrow_drop_up' : 'arrow_drop_down'}
</Icon>
}
</ListItem>
)

请注意 onClickto (react-router 链接)属性的值有条件地归属,因为我们将使用相同的组件来渲染第一层和 NestedItem 的列表。 ,像这样:

const NestedItem = ({ item }) => {
const [collapsed, toggler] = useState(false)
const classes = useStyles()
return (
<div>
<ShallowItem
item={{ icon: item.icon, title: item.title }}
nested
collapsed={collapsed}
onClick={() => toggler(!collapsed)}
/>
<Collapse in={collapsed}>
<List component='div'>
{item.items.map(item => (
<ShallowItem item={item} key={item.title}/>
))}
</List>
</Collapse>

</div>

)}

好了,你明白这个想法了吗?唯一真正被渲染的组件是 ShallowItem原因NestedItem只是一些浅层元素的集合。因此,我们首先渲染一个浅层项目,该项目打开一个折叠容器,其中包含更浅层项目的子列表。现在我们唯一需要做的就是检查该项目是否有子项目,如果是阳性则渲染 NestedItem否则渲染ShallowItem 。该函数是:

const renderItems = items =>{
for(let item of items){
switch(item.type){
case 'nested': return <NestedItem item={item} />

case 'shallow' : return <ShallowItem item={item} />
}
}
}

现在您有了一种递归方式来渲染嵌套项目,您只需要对一个组件进行样式化,并且现在使深度更深变得非常容易。我们在公司使用这个解决方案,它的效果非常好。

关于reactjs - React + Material UI 中的子菜单无法正确关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56287241/

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