如果任何子级具有“ acitve”类,我想在Panel上添加一个类。如果子元素变为“ active”类,如何添加“ parent-active”类。 谢谢您的帮助!
const MyComponent = ({
router,
className,
items
}) => {
return (
<Collapse accordion={true}>
{items.map(dropdown => {
return (
<Panel
header={dropdown.title}
headerClass="dropdown-title"
className={router.pathname === item.href ? 'parent-active' : ''}
key={dropdown.id}
>
{dropdown.dropdownItems.length}
{dropdown.dropdownItems.map(item => (
<Link href={item.href} key={item.id}>
<a
className={
router.pathname === item.href ? 'active' : ''
}
>
{item.label}
</a>
</Link>
))}
</Panel>
);
})}
</Collapse>
);
};
export default withRouter(MyComponent);
答案 0 :(得分:0)
我们可以使用Array.prototype.some()
来确定是否有任何孩子将拥有active
类:
const isAnyChildActive = dropdownItems.some((item) => router.pathname === item.href);
以及完整的代码段:
const MyComponent = ({
router,
className,
items
}) => {
return (
<Collapse accordion={true}>
{items.map(dropdown => {
const { dropdownItems } = dropdown;
const isAnyChildActive = dropdownItems.some((item) => router.pathname === item.href);
return (
<Panel
header={dropdown.title}
headerClass="dropdown-title"
className={isAnyChildActive ? 'parent-active' : ''}
key={dropdown.id}
>
{dropdown.dropdownItems.length}
{dropdown.dropdownItems.map(item => (
<Link href={item.href} key={item.id}>
<a
className={
router.pathname === item.href ? 'active' : ''
}
>
{item.label}
</a>
</Link>
))}
</Panel>
);
})}
</Collapse>
);
};
export default withRouter(MyComponent);