React 导航栏更改活动链接上的背景

mel*_*lis 2 css reactjs

嘿,我刚刚开始学习 React,并且对 HTML、CSS 和 JavaScript 有很好的了解。如果这个导航栏是活动链接,我无法改变颜色,我已经尝试使用几种不同的方法,但没有任何效果对我有用。我有我想要的布局,我只是不知道我是否写错了 JSX 代码,但任何帮助或提示都会很棒,谢谢。

导航栏的 React JSX 代码

import React from "react";
import { Link } from "react-router-dom";

import "./NavBar.scss";

const NavBar = () => {
  return (
    <ul class="tab-bar">
      <Link to="/" className="tab">
        <li>Flash Cards</li>
      </Link>
      <Link to="/sets" className="tab">
        <li>Sets</li>
      </Link>
      <Link to="/new" className="tab">
        <li>New</li>
      </Link>
      <Link to="/about" className="tab">
        <li>About</li>
      </Link>
      <Link to="/login" className="tab">
        <li>Login</li>
      </Link>
    </ul>
  );
};

export default NavBar;
Run Code Online (Sandbox Code Playgroud)

导航栏的 SCSS

$primary-color: #0f9b8e;
$secondary-color: #343837;
$tertiary-color: #03719c;

body {
  background: $secondary-color;
}
.tab-bar {
  margin: 0px;
  padding: 0px;
  display: flex;
  list-style-type: none;
}

.tab {
  width: 100%;
  padding: 20px 0;
  background: $primary-color;
  color: white;
  overflow: hidden;
  text-align: center;
  flex-grow: 1;
  cursor: pointer;
  position: relative;
  text-decoration: none;
}

.tab:hover,
.tab:active {
  background: $tertiary-color;
}
Run Code Online (Sandbox Code Playgroud)

gdh*_*gdh 7

除了使用状态之外,其他选项还有:

1) 只需使用NavLinkactiveClassName. 它会自动读取url并根据你的url路径名调整样式

<NavLink activeClassName="active" className={"tab"} to="/contact">Contact</NavLink>
Run Code Online (Sandbox Code Playgroud)

2)使用useHistoryhook并读取当前url并动态调整样式

...
const currentRoute = useHistory().location.pathname.toLowerCase();
...
<Link className={currentRoute.includes("home") ? "tab active" : "tab"} to="/home"> 
 Home
</Link>
...
Run Code Online (Sandbox Code Playgroud)

代码示例的工作副本(在codesandbox中)

完整代码片段

import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useHistory, NavLink } from "react-router-dom";
import "./styles.scss";
const Nav = props => {
  const currentRoute = useHistory().location.pathname.toLowerCase();
  return (
    <div className="tab-bar">
      <Link
        className={currentRoute.includes("home") ? "tab active" : "tab"}
        active
        to="/home"
      >
        Home
      </Link>
      <Link
        className={currentRoute.includes("about") ? "tab active" : "tab"}
        to="/about"
      >
        About
      </Link>
      <NavLink activeClassName="active" className={"tab"} to="/contact">
        Contact
      </NavLink>
    </div>
  );
};

export default Nav;

Run Code Online (Sandbox Code Playgroud)