Prop to detect if link is active in react

China☆狼群 提交于 2020-08-10 14:00:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!