我按照教程创建了一个React导航栏,当我点击汉堡菜单时,导航栏会按预期展开和折叠,但是当我点击导航菜单上的链接时,它会进入页面,但导航栏不会折叠。我检查了一些问题/指南,但他们都链接到Bootstrap和这段代码不使用Bootstrap,我宁愿不改变导航栏为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 prop:
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 router中的NavLink组件来处理样式。https://reactrouter.com/web/api/NavLink