尝试为孩子设计父 div 的样式Link
if the Link
已应用aria-current="page"
or an active
班级名称。
代码(删除):
<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};
}
`
I tried:
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};
}
`
但这是错误的应用,因为padding-left
。另一种尝试:
<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>
所应用的activeClassName
不渲染在div
and:
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;
}
`
不渲染颜色。
Research
- 样式化组件:如何针对直系儿童? https://stackoverflow.com/questions/58690167/styled-components-how-to-target-direct-children
- Styled-Components:指定父母悬停时孩子的样式 https://stackoverflow.com/questions/45036382/styled-components-specify-styles-of-children-on-parents-hover
- 如何向样式组件添加 aria 属性? https://stackoverflow.com/questions/48083705/how-to-add-an-aria-attribute-to-a-styled-component
- 使用 Material UI 的 makeStyle 设置组件的 [aria-checked="true"] 样式 https://stackoverflow.com/questions/62271948/style-a-components-aria-checked-true-using-material-uis-makestyle
- 样式化组件不适用于层次结构选择器 https://stackoverflow.com/questions/57232729/styled-component-doesnt-work-with-hierachy-selectors
在样式化组件中,有一种方法可以根据子级是否具有 className 来设置父级的样式active
or aria-current="page"
?