英文:
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:
<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>
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论