问题描述
我有一个带有深色背景的白色链接的菜单(用于主页)和带有深色链接的菜单,用于其他所有页面。
无论出于何种原因,react/NextJS 都会在第一页加载时忽略这一点,即使当我控制台路径是“/”时也是如此。有什么建议可以解决这个问题吗?如果我点击主页链接,控制台路径仍然是“/”,我可以获得正确的菜单。
export default function Navigation({menu,className}) {
const {asPath} = useRouter()
const router = useRouter()
const path = router?.asPath // URL from router.
console.log('path',path)
if (path === '/') {
return (
<>
{!!menu?.length && (
<nav className={cn(styles.navigation,className)}>
<ul className="home">
{menu.map((item,index) => {
const children =
item.children && item.children.length > 0 ? item.children : ''
return (
<li key={index}>
<Link href={item.path}>
<a
target={item.target ? item.target : '_self'}
className={cn(
'nav-item',isLinkActive(asPath,item.path) && styles.active
)}
>
{item.label}
</a>
</Link>
{children && (
<ul>
{children.map((item,index) => {
return (
<li key={index}>
<Link href={item.path}>
<a
target={item.target ? item.target : '_self'}
className={cn(
'nav-item',item.path) &&
styles.active
)}
>
{item.label}
</a>
</Link>
</li>
)
})}
</ul>
)}
</li>
)
})}
</ul>
</nav>
)}
</>
)
}
return (
<>
{!!menu?.length && (
<nav className={cn(styles.navigationOther,className)}>
<ul>
{menu.map((item,index) => {
const children =
item.children && item.children.length > 0 ? item.children : ''
return (
<li key={index}>
<Link href={item.path}>
<a
target={item.target ? item.target : '_self'}
className={cn(
'nav-item',item.path) && styles.active
)}
>
{item.label}
</a>
</Link>
{children && (
<ul>
{children.map((item,index) => {
return (
<li key={index}>
<Link href={item.path}>
<a
target={item.target ? item.target : '_self'}
className={cn(
'nav-item',item.path) &&
styles.active
)}
>
{item.label}
</a>
</Link>
</li>
)
})}
</ul>
)}
</li>
)
})}
</ul>
</nav>
)}
</>
)
}
Navigation.propTypes = {
className: PropTypes.string,menu: PropTypes.arrayOf(PropTypes.object)
}
解决方法
您需要使用 react-router-dom 中的位置,然后为您的菜单设置特定的 css 类并相应地使用它:
import { useLocation } from 'react-router-dom'
... 然后在您的导航栏中使用:
className={location.pathName === '/' ? bright-class-name : dark-class-name}