React Router的NavLink保持实现其className方法。

huangapple go评论78阅读模式
英文:

React Router's NavLink keep implemented its className's method

问题

我正在使用React Router版本6.14,遇到了一个奇怪的问题。我是这样使用NavLink的:

<nav>
    <NavLink className={({ isActive }) => isActive ? 'active' : null} to='/host'>Host</NavLink>
    <NavLink className={({ isActive }) => isActive ? 'active' : null} to='/about'>About</NavLink>
    <NavLink className={({ isActive }) => isActive ? 'active' : null} to='/vans'>Vans</NavLink>
</nav>

active的CSS样式简单如下:

.active {
  color: #161616;
  text-decoration: underline;
}

问题是,如果我从NavLink中删除className属性,它的样式仍然生效。即使我重新启动程序,它仍然发生,就好像它记住了那行代码。只有当我从CSS文件中删除active部分时,它才停止。

有人了解这个奇怪的错误吗?

英文:

I'm using React Router version 6.14, and I have a weird issue. I'm using the NavLink in this way:

&lt;nav&gt;
    &lt;NavLink className={ ({isActive}) =&gt; isActive ? &#39;active&#39; : null } to=&#39;/host&#39;&gt;Host&lt;/NavLink&gt;
    &lt;NavLink className={ ({isActive}) =&gt; isActive ? &#39;active&#39; : null } to=&#39;/about&#39;&gt;About&lt;/NavLink&gt;
    &lt;NavLink className={ ({isActive}) =&gt; isActive ? &#39;active&#39; : null } to=&#39;/vans&#39;&gt;Vans&lt;/NavLink&gt;
&lt;/nav&gt;

The CSS of the 'active' is simply:

.active {
  color: #161616;
  text-decoration: underline;
}

The problem is if I remove the className attribute from the NavLink, its method still being implemented. Even if I restart the program it's still hapening, like it's remember that line of code. Only if I remvoe the 'active' section from the CSS file it stops.

Does anyone know anything about this strange bug?

答案1

得分: 0

多亏了 @Drew Reese 的帮助,这个问题得到了解答。我将在这里分享解决方案,以便其他人遇到类似问题时可以参考。原来,默认情况下,NavLink 组件在激活时会自动添加一个 active 类。这就是为什么如果 CSS 文件中有一个叫做 "active" 的类,它会影响到激活的 NavLink,即使没有为其定义 className。

相关文档链接:default-active-class

英文:

Thanks to @Drew Reese the question is answered, I'll share the solution here in case others come across it. It turns out that by default, an active class is added to a NavLink component when it is active. That's why if there's a class in the CSS file called "active", it will affect the active NavLink, even if there's no definition to its className.

The documentation that refer to this: default-active-class

huangapple
  • 本文由 发表于 2023年6月29日 05:32:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定