React Router v4 <NavLink> 对比 <Link> 优势

React Router v4 <NavLink> vs <Link> benefits

除了可以在 NavLink 上设置 "activeClassName" 和 "activeStyle" 之外,还有什么理由使用 NavLinkLink 上创建指向您网站上不需要活动的非导航元素(即页眉或页脚中的主导航)的其他路线的链接时state/class?

official documentation清楚:

<NavLink>

A special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL.

因此,答案是。除了上述原因外,没有其他原因。

当您需要在活动 <Link> 上使用样式或 class 属性时,您可以使用 <NavLink>

让我们看例子:

Link

<Link to="/">Home</Link>

导航Link

<NavLink to="/" activeClassName="active">Home</NavLink>

很简单, 当您使用 <Link> 时,所选元素上没有任何 active class。
相比之下,使用 <NavLink> 时,所选元素会突出显示,因为此元素已添加为活动 class。
希望对你有用。

Link 组件

It is used to create links which allow to navigate on different URLs and When we click on any of that particular Link, it should load that page which is associated with that path without reloading the page. Example:

导航Link 分量:

If, we want to add some styles to the Link. So that when we click on any particular link, it can be easily identified which Link is active. For this react router provides NavLink instead of Link. Now replace Link from Navlink and add properties activeStyle. The activeStyle properties mean when we click on the Link, it should be highlighted with different style so that we can differentiate which link is currently active. Example:

参考:https://www.javatpoint.com/react-router

v6.0.0-beta.3 的一个区别是 activeClassName 和 activeStyle 已从 NavLinkProps 中删除。相反,您可以将函数传递给 style 或 className,这将允许您根据组件的活动状态自定义内联样式或 class 字符串。您还可以将一个函数作为子项传递,以根据组件的活动状态自定义组件的内容,这对于更改内部元素的样式特别有用。

只是为了在 v6 中添加,NavLink.active class 添加到 a 标签,无需任何额外的代码,例如

<NavLink to="/">Link 1</Link>
<NavLink to="/link2">Link 2</Link>

将呈现为:

<a href="/" className='active'>Link 1</Link>
<a href="/link2">Link 2</Link>

如果用户在家里 URL (https://localhost:3000)