ReactJS 中的类别和子类别 [英] categories and sub categories in ReactJS
问题描述
你好,我正在尝试使用 Material ui 制作侧边栏菜单
Hello I'm trying to make a sidebar menu using material ui
此侧边栏菜单包含类别和子类别.
This sidebar menu contain categories and there sub categories.
我有这样的代码:
我想要做什么?
我从我的 Laravel API 中获取了一些类别数据,在每个类别上他们可以有一个子类别的对象,我折叠它以显示来自父类别的子类别
如果我每一个折叠一个折叠,这是正常的,因为它们共享相同的状态,但我不知道如何为每个父类别制作一个状态
const categoriesList = this.state.categories.map((item, k) => {
return (
<React.Fragment key={k}>
<ListItem button onClick={this.handleClick}>
<ListItemText primary={item.label} />
{item.category !== null ? this.state.open ? <ExpandLess /> : <ExpandMore /> : null}
</ListItem>
{item.category !== null ? <>
<Collapse in={this.state.open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{item.category.map((ite,l) => <ListItem key={l} button className={classes.nested}><ListItemText primary={ite.label} /></ListItem>)}
</List>
</Collapse>
</> : null}
</React.Fragment>
)
})
``
推荐答案
我建议您为每个类别创建一个组件.因此,您将拥有:
I would recommend that you create a component for each category. So instead you would have:
const categoriesList = this.state.categories.map((item, k) => {
return <Category key={k} {...item} />;
});
在你的代码的其他地方,你会有另一个组件:
And elsewhere in your code you'd have another Component:
const Category = (props) => {
const [open, setOpen] = useState(false);
function handleClick(e) { ... }
return (
<React.Fragment>
<ListItem button onClick={handleClick}>
<ListItemText primary={props.label} />
{props.category !== null ? open ? <ExpandLess /> : <ExpandMore /> : null}
</ListItem>
{item.category !== null ? <>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{props.category.map((ite,l) => <ListItem key={l} button className={classes.nested}><ListItemText primary={ite.label} /></ListItem>)}
</List>
</Collapse>
</> : null}
</React.Fragment>
);
}
然后状态包含在 Category 组件中,您可以保持容器组件简单.
Then the state is contained with the Category component, and you can keep your container component simple.
[注意] 我更喜欢函数组件,所以在这里使用它,但类组件不会改变这个答案.
[note] I prefer function components, so used that here, but a Class Component wouldn't change this answer.
这篇关于ReactJS 中的类别和子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!