我有一个使用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'
呢?为什么会发生这种情况,如何纠正?
1条答案
按热度按时间k2arahey1#
使用
NavLink
组件,它默认为匹配的链接应用"active"
类名,并使用CSS选择具有当前匹配链接的li
元素。范例:
个字符
信息说明:
Demo
的数据
的
由于您使用的是SASS,因此这似乎是您正在使用的正确CSS:
型
的