问题描述
当您位于 NavLink 链接到的页面时,React Router 会向它们添加 active
类.如何使用样式化组件访问此属性.当您在他们的页面上时,我需要对菜单项进行不同的样式设置.
React Router adds an active
class to NavLinks when you are on the page that they link to. How can I access this property with Styled Components. I need to styled menu items differently when you are on their page.
const LinkElem = styled(NavLink)`
font-size: 16px;
font-weight: 400;
${props => console.log(props)};
&:hover {
color: ${props => props.theme.colorOrange};
}
`;
const Menu = props => {
const { me } = props;
return (
<MenuElem>
<li>
{me ? (
<LinkElem to="/account">Account</LinkElem>
) : (
<LinkElem to="/login">Log in / sign up</LinkElem>
)}
</li>
</MenuElem>
);
};
推荐答案
我不是特别热衷于 &.active
方法,如果你想构建一个样式化组件路由器独立,所以我创建了 asNavLink
来处理与此:
I'm not particularly keen on the &.active
approach if you're trying to build a styled-component that is router independent, so I created asNavLink
to deal with this:
npm install as-nav-link --save
给定一个组件:
const MyNavAnchor = styled(({
as: T = 'a',
active, // destructured so it is not passed to anchor in props
...props
}) => <T {...props} />)({
textDecoration: 'blink',
color: 'blue',
}, ({ active }) => (active && {
color: 'red',
}));
你可以这样使用它:
import asNavLink from 'as-nav-link';
const MyNavLink = asNavLink(config)(MyNavAnchor);
它会将活动道具传递给您的样式组件.
And it will pass down the active prop to your styled component.
config
是可选的,可以包含一个 isActive
函数(根据 ReactRouter 的 NavLink)和一个 activeProp
字符串(传递的道具名称到您的组件).
config
is optional and can include an isActive
function (as per ReactRouter's NavLink) and an activeProp
string (the prop name that is passed to your component).
这篇关于在样式化组件中使用来自 React Router 的“活动"状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!