简体   繁体   English

如何在 nextjs 中添加活动的 className

[英]How to add active className in nextjs

I am new to Nextjs.我是 Nextjs 的新手。 I have to have an active className when a nav-link is selected.选择导航链接时,我必须有一个活动的类名。 I am using Nextjs+react-bootstrap in my project.我在我的项目中使用 Nextjs+react-bootstrap。 The feature I want to implement is when someone clicks on a specific link it's colour should be changed我要实现的功能是当有人点击特定链接时,它的颜色应该改变

my Navbar component looks like this -我的导航栏组件看起来像这样 -

 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;

This special version of the Link tag is called NavLink and adds styling attributes to the rendered element when it matches the current URL这个特殊版本的 Link 标签称为 NavLink,当它与当前的 URL 匹配时,它会向渲染元素添加样式属性

The class is given to the element when it is active by writing: class 在元素处于活动状态时通过写入:

<NavLink to="/about" activeClassName="active">
  About
</NavLink>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM