React Router Dom v6 显示索引和其他子路由处于活动状态

Dee*_*tye 12 reactjs react-router react-router-dom

<Route path='/dashboard' element={<Navbar />}>
     <Route index element={<Home />} />
     <Route path='profile' element={<Profile />} />
     <Route path='wallets' element={<Wallet />} />
     <Route path='users' element={<Users />} />
</Route>
Run Code Online (Sandbox Code Playgroud)

这是我的代码,基本上发生的事情是在我的导航栏中我将活动页面链接标记为蓝色所以当我在上面时,/dashboard主页显示为蓝色但是当我在上面时,/dashboard/profile它显示主页和个人资料都为蓝色

<li>
    <NavLink to=''>
      {({ isActive }) =>
         isActive ? (
               <text style={{color: blue}}>Home</text>
         ) : (                      
               <text>Home</text>
         )
      }
    </NavLink>
</li>
<li>
    <NavLink to='profile'>
    {({ isActive }) =>
         isActive ? (
               <text style={{color: blue}}>Profile</text>
         ) : (                      
               <text>Profile</text>
         )
    }
    </NavLink>
</li>
                      
Run Code Online (Sandbox Code Playgroud)

Dre*_*ese 27

end您可以在路径的“根”级链接上指定prop "/dashboard"

导航链接

如果end使用该属性,它将确保在匹配其后代路径时该组件不会被匹配为“活动”。

<NavLink to='' end>
  {({ isActive }) =>
     isActive ? (
           <text style={{color: blue}}>Home</text>
     ) : (                      
           <text>Home</text>
     )
  }
</NavLink>
Run Code Online (Sandbox Code Playgroud)

编辑react-router-dom-v6-shows-active-for-index-as-well-as-other-subroutes