reactjs - NavLink 在 React Router DOM 中的多个 URL 的同一链接上处于活动状态
问题描述
我有一个包含多个标签(子)的页面。我还更改了每个选项卡的 URL,但我仍在父页面上,只是更改了选项卡的 URL。
问题是当我单击选项卡时无法保持父页面 NavLink 处于活动状态,因为它会更改 URL,但我想在选项卡 URL 上保持该活动。
这该怎么做?
从“反应”导入反应;从 'react-router-dom' 导入 { NavLink };
export default () => {
return (
<>
<nav className='Navigation'>
<ul className={`Navigation__list ${hide}`}>
<li className='Navigation__list-item'>
<NavLink to="/events" >Events</NavLink>
</li>
</ul>
</nav>
<Tabs />
</>
);
}
// 标签组件作为子组件
export default function Tabs () => (
<ul className="events__tab">
<li> <NavLink to="/events"> All Events </NavLink> </li>
<li> <NavLink to="/myevents"> My Events </NavLink> </li>
</ul>
)
感谢您的提前支持!
解决方案
你所要做的就是在里面写一个条件isActive
,NavLink
如果当前页面的 URL 与定义的 URL 匹配,则返回true
else false
。使用里面的函数isActive
,如果它返回true,你将获得活动链接。示例:
isActive={ () => ['/example', '/exampl2'].inclues(currentPageUrl) }
if the current URL matches in the Above Array, your NavLink will be Active as long as URL doesn't match.
for finding the Current Page URL use the useLocation()
hook.
import React from 'react';
import { useLocation } from 'react-router-dom';
// Active the Link on two URLs
export default () => {
// extract pathname from location
const { pathname } = useLocation();
return (
<li className='Navigation__list-item'>
<NavLink
to="/events"
isActive={() => ['/events', '/myevents'].includes(pathname)} >
Events
</NavLink>
</li>
);
};
推荐阅读
- android - Android - 当应用程序在 Google Playstore 中自动更新时如何在应用程序中获取回调
- javascript - 从 JavaScript 中的 UDP 套接字中提取 double 类型的数组
- macos - NSTextView 在断字时总是使用系统语言?
- javascript - 由于 PythonAnywhere 的响应上限为 5 分钟,我如何递归调用我的一个 Classful 方法作为一个全新的请求
- python - Discord.py 信息存储
- python - 将 lambda 函数的结果插入 postgres 表
- node.js - 在 AWS Lambda 中运行 elasticdump(节点可执行文件)
- arrays - (&array)[1] 到底是什么?
- sql - SSRS 从数据集中插入特定值
- python - 有没有办法让你的机器人通过命令跟踪其他服务器的公告频道?