首页 > 解决方案 > ReactJS 中的类别和子类别

问题描述

您好,我正在尝试使用材质 ui 制作侧边栏菜单

此侧边栏菜单包含类别和子类别。

我有这个代码:

我想做什么?

I take some categories data from my Laravel API, on each categories they can have an object of sub categories, and I collapse this to show the sub categories from the parent category

If I collapse one every one collapse, this is normal because they share the same state, but I don't know how to make one state for each parent categories

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>
            )
        })
``

标签: reactjsapi

解决方案


我建议您为每个类别创建一个组件。因此,您将拥有:

const categoriesList = this.state.categories.map((item, k) => {
    return <Category key={k} {...item} />;
});

在你的代码的其他地方你会有另一个组件:

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 组件中,您可以使容器组件保持简单。

[注意] 我更喜欢函数组件,所以在这里使用,但类组件不会改变这个答案。


推荐阅读