如果Link
具有应用的aria-current="page"
或active
类名,则尝试为子级的Link
设置父div样式。
代码(剥离(:
<NavBody>
{items.map((subItem, key) => {
const { title, link } = subItem
return (
<NavLinkContainer key={key}>
<NavLink
onClick={closeMobileMenu}
to={`/docs${link}`}
activeClassName="active"
>
{title}
</NavLink>
</NavLinkContainer>
)
})}
</NavBody>
造型组件:
const NavBody = styled(Accordion.Body)`
margin-left: ${({ theme }) => theme.spacings.small};
padding: 0 !important;
`
const NavLinkContainer = styled.div`
padding-top: ${({ theme }) => theme.spacings.xSmall};
padding-bottom: ${({ theme }) => theme.spacings.xSmall};
border-left: 1px solid ${({ theme }) => theme.colors.color7};
padding-left: ${({ theme }) => theme.spacings.small} !important;
`
const NavLink = styled(Link)`
color: ${({ theme }) => theme.colors.color3};
text-decoration: none;
padding-bottom: ${({ theme }) => theme.spacings.xxSmall};
&.active {
color: ${({ theme }) => theme.colors.color1};
}
&:hover {
color: inherit;
opacity: 0.7;
text-decoration: none;
border-bottom: 1px solid ${({ theme }) => theme.colors.color1};
}
`
我试过了:
const NavLinkContainer = styled.div`
padding-top: ${({ theme }) => theme.spacings.xSmall};
padding-bottom: ${({ theme }) => theme.spacings.xSmall};
border-left: 1px solid ${({ theme }) => theme.colors.color7};
padding-left: ${({ theme }) => theme.spacings.small} !important;
&.active {
border-left: 1px solid ${({ theme }) => theme.colors.color1};
}
`
但是由于CCD_ 5的原因而被错误地应用。另一种尝试:
<NavBody>
{items.map((subItem, key) => {
const { title, link } = subItem
return (
<NavLinkContainer key={key} activeClassName="active">
<NavLink
onClick={closeMobileMenu}
to={`/docs${link}`}
activeClassName="active"
>
{title}
</NavLink>
</NavLinkContainer>
)
})}
</NavBody>
所应用的CCD_ 6不在CCD_
const NavLinkContainer = styled.div`
padding-top: ${({ theme }) => theme.spacings.xSmall};
padding-bottom: ${({ theme }) => theme.spacings.xSmall};
border-left: 1px solid ${({ theme }) => theme.colors.color7};
padding-left: ${({ theme }) => theme.spacings.small} !important;
&[aria-current='page'] {
border-left: 3px solid ${({ theme }) => theme.colors.color1} !important;
}
`
不会渲染颜色。
研究
- 样式化组件:如何针对直接子级
- 样式化组件:在父对象悬停时指定子对象的样式
- 如何将aria属性添加到已设置样式的组件中
- 使用Material UI的makeStyle为组件的[aria checked="true"]设置样式
- 样式化组件不适用于层次选择器
在样式化组件中,是否有一种方法可以根据子级的className是active
还是aria-current="page"
对父级进行样式化?
我想好了如何修改我的父NavLinkContainer
。在Reach路由器中,我可以从useLocation
:访问pathname
const { pathname } = useLocation()
使用地图中的link
和useMemo
,我可以通过设置变量来确定link
是否存在
const active = useMemo(() => {
return pathname.toString().includes(link)
}, [pathname, link])
通过这样做,我可以将布尔值传递给NavLinkContainer
:
<NavLinkContainer border={active}>
// Further code
</NavLinkContainer>
在样式化组件中,我可以做到:
const NavLinkContainer = styled.div`
border-color: ${({ border, theme }) =>
border ? `${theme.colors.color1}` : `${theme.colors.color5}`};
`
这使我能够在我的主题中使用自定义边框颜色集来设计父CCD_ 17的样式。