如何在react-router自定义链接上添加悬停效果?



我使用react router custom link for来突出显示导航栏中的活动路径/链接,一切工作正常。但是我不能在这些链接上添加悬停效果。我使用.nav-link a:hover并尝试添加一些样式,但它不起作用。


const CustomLink = ({ children, to, ...props }) => {
let resolved = useResolvedPath(to);
let match = useMatch({ path: resolved.pathname, end: true });

return (
<div className="nav-link">
<Link
style={{
textDecoration: match ? "underline" : "none",
color: match ? "#FDC300" : "white",
fontWeight: match ? 500 : 400
}}
to={to}
{...props}
>
{children}
</Link>
</div>
);
};

export default CustomLink;

不要通过style属性来样式化它们,因为这比任何css规则(除非您诉诸!important)具有更高的专一性。

只需添加一个类来表示它是活动的。

const CustomLink = ({ children, to, ...props }) => {
let resolved = useResolvedPath(to);
let match = useMatch({ path: resolved.pathname, end: true });
const linkClassNames = match ? 'active' : '';
return (
<div className=`nav-link ${linkClassNames}`>
<Link
to={to}
{...props}
>
{children}
</Link>
</div>
);
};

export default CustomLink;
.nav-link a {
text-decoration: none;
color: white;
font-weight: 400;
}
.nav-link.active a {
text-decoration: underline;
color: #FDC300;
font-weight: 500;
}

你可以使用NavLink组件(由react路由器提供的)来支持这个

<NavLink
to="wherever you want"
className={({ isActive }) =>
isActive ? 'nav-link active' : 'nav-link'
}
>
your link text here
</NavLink>

最新更新