当特定路由被访问时,我希望能够根据条件渲染两个不同的组件,或者改变两个出口。
你可以在该特定路由上实现这一功能。在element
属性上使用三元运算符来条件性地渲染组件。同时,每个布局路由一次只能渲染一个出口。
示例代码如下:
<Routes>
...
<Route element={<Layout />}>
...
<Route
path="/somePath"
element={
someCondition
? <ComponentA />
: <ComponentB />
}
/>
...
</Route>
...
</Routes>
当然,你也可以将此逻辑抽象为一个组件。
const SomeComponent = () => {
...
return someCondition
? <ComponentA />
: <ComponentB />;
};
然后在路由中使用这个组件:
<Routes>
...
<Route element={<Layout />}>
...
<Route path="/somePath" element={<SomeComponent />} />
...
</Route>
...
</Routes>
关于NavLink
的isActive
属性问题,我希望当路由处于激活状态时,某个div
可见或显示。
NavLink
组件的children
属性也可以接受一个函数,类似于className
(以及style
)属性。
<NavLink
to="/"
onClick={handleHomeClick}
className={({ isActive }) =>
`block py-2 pr-4 pl-3 duration-200 ${isActive ? "text-orange-700" : "text-gray-700"} border-b border-gray-100 hover:bg-gray-50 lg:hover:bg-transparent lg:border-0 hover:text-orange-700 lg:p-0`
}
aria-current="page"
>
HOME
{({ isActive }) => isActive && (
<div className="absolute top-full left-1/2 transform -translate-x-1/2 w-2 h-2 mt-1 border-2 border-yellow-500 bg-black rotate-45" />
)}
</NavLink>