React Navbar 在 Link 单击时不折叠

React Navbar Not Collapsing On Link Click

我按照教程创建了一个 React NavBar,当我单击汉堡菜单时,导航会按预期展开和折叠,但是当我单击导航菜单上的 link 时,它会转到页面,但导航栏不会折叠。我已经检查了一些 questions/guides 但它们都是 link 到 Bootstrap 并且此代码不使用 Bootstrap,我不想将 NavBar 更改为 Bootstrap 如果可以避免的话!任何帮助将不胜感激。

import React, { Component } from "react";
import logo from "../images/logo.svg";
import { FaAlignRight } from "react-icons/fa";
import { Link } from "react-router-dom";

export default class Navbar extends Component {
  state = {
    isOpen: false
  };
  handleToggle = () => {
    this.setState({ isOpen: !this.state.isOpen });
  };

  componentDidMount() {
    window.addEventListener("scroll", this.resizeHeaderOnScroll);
    window.addEventListener("scroll", this.navTransparent);
    window.addEventListener("scroll", this.navShadow);
  };
  resizeHeaderOnScroll() {
    const distanceY = window.pageYOffset || document.documentElement.scrollTop,
      shrinkOn = 100,
      headerEl = document.getElementById("logo");
    if (distanceY > shrinkOn) {
      headerEl.classList.add("logoShrink");
      
    } else {
      headerEl.classList.remove("logoShrink");
    }
  }

  navTransparent() {
    const distanceY = window.pageYOffset || document.documentElement.scrollTop,
      shrinkOn = 100,
      headerEl = document.getElementById("navbar");
    if (distanceY > shrinkOn) {
      headerEl.classList.add("navbarBg");
      
    } else {
      headerEl.classList.remove("navbarBg");
    }

  }
  
  navShadow() {
    const distanceY = window.pageYOffset || document.documentElement.scrollTop,
      shrinkOn = 100,
      headerEl = document.getElementById("navbar");
    if (distanceY > shrinkOn) {
      headerEl.classList.add("navShadow");
      
    } else {
      headerEl.classList.remove("navShadow");
    }
  }
  render() {
    return <nav id="navbar">
      <div className="nav-center">
        <div className="nav-header">
          <Link to="/">
            <img id="logo" src={logo} alt="" />
          </Link>
          <button type="button" className="nav-btn" onClick={this.handleToggle}>
            <FaAlignRight className="nav-icon" />
          </button>
        </div>
        <ul className={this.state.isOpen ? "nav-links show-nav" : "nav-links"}>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/nigelservices">Services</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
          </ul>
      </div>
    </nav>;
  }
}

要回答这里的问题,你总是可以这样做,因为 Link 组件接受 onClick 属性:

export default class Navbar extends Component {
 // Rest of your code
 handleLinkClick = () => {
  this.setState({ isOpen: false });
 };

 render() {
  return (
  // Your JSX
   <Link to="/" onClick={handleLinkClick}>Home</Link>
  )
 }
}

记得在每个 link 组件中添加这个。

作为旁注,您还可以在 React 路由器中使用 NavLink 组件来处理当前路由时的样式。 https://reactrouter.com/web/api/NavLink