如何在反应中有条件地设置主页项目按钮的样式?
How to get the home page item button conditionally styled in react?
我正在使用 React 和 Material UI 渲染导航栏,并尝试根据 url 有条件地为所选菜单项提供样式。
我正在使用 useLocation 获取当前 url:
import { Link, useLocation } from 'react-router-dom';
const location = useLocation();
const menuItem = ['Pool', 'Mining', 'Leveraged', 'Lock-up', 'Docs', 'Profile'];
然后我有条件地重定向到 url,如果 url 是池,那么我希望它重定向到主页('/')。
{menuItem.map((item) => (
<MenuItem
classes={{
selected: classes.selected,
}}
component={Link}
to={item === 'Pool' ? '/' : `${item}`}
key={item}
selected={location.pathname === `/${item}`}
>
{item}
</MenuItem>
))}
问题是虽然所选样式适用于所有路径名,但不适用于 pool 主页。
这是我根据 url
选择项目时得到的结果(白色边框)
虽然唯一没有设置样式的菜单项是主页
对于您当前问题的特定解决方案,您需要修改 selected=
中的条件以包含您想要的情况,例如 || (item === 'Pool' && location.pathname === '/')
或类似的内容。您可能需要 fiddle 。
作为更广泛的答案,考虑使用 react-router 的内置 NavLink component. They already have an isActive prop 专门用于处理像这样的复杂情况。重新发明轮子没有意义。
你可以试试
selected={item === 'Pool' ? location.pathname === '/' : location.pathname === `/${item}`}
我正在使用 React 和 Material UI 渲染导航栏,并尝试根据 url 有条件地为所选菜单项提供样式。 我正在使用 useLocation 获取当前 url:
import { Link, useLocation } from 'react-router-dom';
const location = useLocation();
const menuItem = ['Pool', 'Mining', 'Leveraged', 'Lock-up', 'Docs', 'Profile'];
然后我有条件地重定向到 url,如果 url 是池,那么我希望它重定向到主页('/')。
{menuItem.map((item) => (
<MenuItem
classes={{
selected: classes.selected,
}}
component={Link}
to={item === 'Pool' ? '/' : `${item}`}
key={item}
selected={location.pathname === `/${item}`}
>
{item}
</MenuItem>
))}
问题是虽然所选样式适用于所有路径名,但不适用于 pool 主页。
这是我根据 url
选择项目时得到的结果(白色边框)虽然唯一没有设置样式的菜单项是主页
对于您当前问题的特定解决方案,您需要修改 selected=
中的条件以包含您想要的情况,例如 || (item === 'Pool' && location.pathname === '/')
或类似的内容。您可能需要 fiddle 。
作为更广泛的答案,考虑使用 react-router 的内置 NavLink component. They already have an isActive prop 专门用于处理像这样的复杂情况。重新发明轮子没有意义。
你可以试试
selected={item === 'Pool' ? location.pathname === '/' : location.pathname === `/${item}`}