reactjs 如何在React-Router中设置活动类?

e5nqia27  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(118)

我有一个使用React-Router创建的导航
nav.tsx

import React from 'react'
import { menu } from './menu'
import { Link } from 'react-router-dom'
import styles from './HamburgerMenu.module.scss'

const HamburgerMenu: React.FC = () => {
  const [active, setActive] = React.useState<number>(0)
  console.log(active)

  return (
    <nav>
      <ul className={styles.menu}>
        {menu.map((item, index) => (
          <li
            onClick={() => setActive(index)}
            key={item.title}
            className={styles[active === index ? 'active' : '']}
          >
            <Link to={item.link}>{item.title}</Link>
          </li>
        ))}
      </ul>
    </nav>
  )
}

export default HamburgerMenu

字符串
menu.ts:

export const menu: IMenuItem[] = [
  {
    link: '/',
    title: 'главная'
  },
  {
    link: '/profile',
    title: 'профиль'
  },
  {
    link: '/discipline',
    title: 'наказания'
  },
  {
    link: '/store',
    title: 'магазин'
  },
  {
    link: '/statistics',
    title: 'статистика'
  }
]


main.tsx:

import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createBrowserRouter } from 'react-router-dom'
import Home from './pages/Home/Home'
import './assets/style/global.scss'
import NotFoundPage from './pages/NotFoundPage'
import Profile from './pages/Profile/Profile'

const router = createBrowserRouter([
  {
    element: <Home />,
    path: '/'
  },
  {
    element: <Profile />,
    path: '/profile'
  },
  {
    element: <NotFoundPage />,
    path: '*'
  }
])

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
)


style.scss

.menu {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10;
    margin-right: 100px;

    li.nav-link-item {
        margin: 0px 50px;
        a {
            color: $white;
            opacity: 0.7;
            transition: opacity 0.3s ease;
            font-size: 20px;

            &:hover {
                opacity: 1;
            }
        }
    }

    li.nav-link-item:has(a.active) {
        border-radius: 10px;
        border: 5px solid #542c44;
        padding: 7px 42px;
    }
}


Layout.tsx -页面转到它

import React from 'react'
import { ILayoutProps } from './Laout.type'
import Header from '../Header/Header'
import Footer from '../Footer/Footer'
import styles from './Layout.module.scss'

const Layout: React.FC<ILayoutProps> = ({ children }) => {
    return (
        <div className={styles['layout']}>
            <Header />
            {children}
            <Footer />
        </div>
    )
}

export default Layout


当在'/''/profile'之间切换时,"active"类不断重置并切换为0,如果我想将"active"类添加到'/profile',那么我需要点击它2次,如果我在'/discipline''/store''/statistics'之间切换,我知道这种行为很可能是由于'/discipline''/store''/statistics'没有声明页面,但是'/''/profile'呢?为什么会发生这种情况,如何纠正?

k2arahey

k2arahey1#

使用NavLink组件,它默认为匹配的链接应用"active"类名,并使用CSS选择具有当前匹配链接的li元素。
范例:

const HamburgerMenu: React.FC = () => {
  return (
    <nav>
      <ul className={styles.menu}>
        {menu.map((item, index) => (
          <li
            key={item.title}
            className="nav-link-item" // <-- something easily targetable
          >
            <NavLink end to={item.link}>
              {item.title}
            </NavLink>
          </li>
        ))}
      </ul>
    </nav>
  );
};

个字符
信息说明:

Demo


的数据



由于您使用的是SASS,因此这似乎是您正在使用的正确CSS:

li.nav-link-item {
  margin: 0px 50px;

  a {
    color: #fff;
    opacity: 0.7;
    transition: opacity 0.3s ease;
    font-size: 20px;

    &:hover {
      opacity: 1;
    }
  }

  &:has(:global(a.active)) { // <-- access global non-SASS "active" class
    border-radius: 10px;
    border: 5px solid #542c44;
    padding: 7px 42px;
  }
}


相关问题