我是Nextjs的新手。当选择导航链接时,我必须有一个活动的类名。我在我的项目中使用Nextjs+react引导程序。我想实现的功能是,当有人点击特定链接时,它的颜色应该更改
我的导航栏组件看起来像这样-
import React from "react";
import { Navbar, Nav, Button } from "react-bootstrap";
import Link from "next/link";
import "../../styles/Header.module.css";
const Header = () => {
return (
<div className="header">
<Navbar expand="lg">
<Link href="/">
<Navbar.Brand style={{ padding: "8px 50px" }}>
<img
src="/logo.svg"
left="60px"
top="25px"
width="112px"
height="23px"
className="d-inline-block align-top"
alt="Openhouse logo"
/>
</Navbar.Brand>
</Link>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav" className="justify-content-end">
<Nav className="ml-auto">
<Link href="/classes" passHref>
<Nav.Link style={{ padding: "8px 50px" }}>Classes</Nav.Link>
</Link>
<Link href="/clubs" passHref>
<Nav.Link style={{ padding: "8px 50px" }}>Clubs</Nav.Link>
</Link>
<Link href="/aboutUs" passHref>
<Nav.Link style={{ padding: "8px 50px" }}>AboutUs</Nav.Link>
</Link>
</Nav>
<Button variant="warning" size="sm">
Chat with us
</Button>
</Navbar.Collapse>
</Navbar>
</div>
);
};
export default Header;
这个特殊版本的Link标签被称为NavLink,当它与当前URL 匹配时,它会为渲染元素添加样式属性
当元素处于活动状态时,通过写入将类赋予该元素
<NavLink to="/about" activeClassName="active">
About
</NavLink>'