如何解决反应忽略路径导致错误的菜单显示
我有一个带有深色背景的白色链接的菜单(用于主页)和带有深色链接的菜单,用于其他所有页面。
无论出于何种原因,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}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。