首页 > 解决方案 > 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>
)

感谢您的提前支持!

标签: reactjsreact-routerreact-router-dom

解决方案


你所要做的就是在里面写一个条件isActiveNavLink如果当前页面的 URL 与定义的 URL 匹配,则返回trueelse 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>
    );
};

推荐阅读