问题
I have a NavLink
which have child components
<NavLink
className={StyledAppNavItem}
activeClassName={StyledAppNavItemActive}
to={link.path}
>
<Icon size={28} icon={link.icon} color={isActive?'red':'blue'}/>
<StyledAppNavName>{link.name}</StyledAppNavName>
</NavLink>
Like activeClassName
is attached when the link is active, I need to detect if this link is active and send a prop to its child component Icon
Somewhat like <Icon color={linkisActive?'red':'blue'}/>
回答1:
Unfortunately, there is no way to get isActive
from NavLink
. You need to create your custom NavLink
. Something like this:
function MyNavLink() {
return (
<Route path={link.path} children={({ match }) => (
<Link
className={`${StyledAppNavItem} ${match ? StyledAppNavItemActive : ''}`}
to={link.path}
>
<Icon size={28} icon={link.icon} color={match ? 'red' : 'blue'}/>
<StyledAppNavName>{link.name}</StyledAppNavName>
</Link>
)} />
);
}
Or you can just add Route to your current component:
<NavLink
className={StyledAppNavItem}
activeClassName={StyledAppNavItemActive}
to={link.path}
>
<Route path={link.path} children={({ match }) => (
<Icon size={28} icon={link.icon} color={match?'red':'blue'}/>
)} />
<StyledAppNavName>{link.name}</StyledAppNavName>
</NavLink>
来源:https://stackoverflow.com/questions/48747114/prop-to-detect-if-link-is-active-in-react