【问题标题】:How to remove NavLink styling for unselected Routes如何删除未选择路线的 NavLink 样式
【发布时间】:2022-01-08 09:24:17
【问题描述】:

我想知道如何恢复到下面屏幕截图中标记的 NavLink 的默认样式。 color 应该是白色的并且没有下划线。您会在屏幕截图下方找到我的代码: Home 是当前选择的默认路径。其上的 activeClass 属性正在正常工作。

代码:

const NavBar = () => {
    return(
        <div className="navBar">
            <div className="logo">LOGO</div>
            <div className="navOptions">
                <ul>
                    <li>
                        <NavLink exact activeClassName="activeClass" to="/">Home</NavLink>
                    </li>
                    <li>
                        <NavLink exact activeClassName="activeClass" to="/advanceFilter">Advanced Search</NavLink>
                    </li>
                    <li>
                        <NavLink exact activeClassName="activeClass" to="viewAll">View All</NavLink>
                    </li>
                    <li>Logout</li>
                </ul>
            </div>
        </div>
    );
}

export default NavBar;

CSS:

.navBar {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 100%;
    color: white;
    font-weight: bold;
}

.logo {
    display: flex;
    flex: 1;
    align-items: center;
    padding-left: 50px;
}

.navOptions {
    display: flex;
    justify-content: flex-end;
    flex: 1;
    height: 100%;
}

//The li items don't have the color and text-decoration properties on them
li {
    display: inline;
    margin-right: 20px;
    cursor: pointer;
    height: 100%;
    text-decoration: none;
    color: white;
}

li:hover {
    background-color: gray;
}

ul {
    margin-right: 40px;
    list-style-type: none;
}

.activeClass {
    text-decoration: none;
    color: purple;
}

【问题讨论】:

  • NavLink 元素在 activeClassName 属性旁边接受 className 属性,并编译为 a 标记 - 您可以将样式添加到 a 元素或添加自定义类通过className

标签: css reactjs react-router-dom


【解决方案1】:

NavLink 组件呈现一个锚点 &lt;a /&gt; 标记,更新 CSS 中的选择器以同时定位作为 li 元素子级的锚点标记。

li, li a {
  display: inline;
  margin-right: 20px;
  cursor: pointer;
  height: 100%;
  text-decoration: none;
  color: white;
}

或者,您也可以指定一个“navlink”类并在那里应用默认的非活动 CSS 样式。

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2014-06-13
    相关资源
    最近更新 更多