【问题标题】:Set active link in React Router based on current path根据当前路径在 React Router 中设置活动链接
【发布时间】:2021-11-15 05:41:22
【问题描述】:

使用 React Router 和 Material UI,我正在尝试根据当前 URL 路径设置导航项选择状态。如果用户来到一个特定的页面,它应该在侧边栏中设置相应链接的选中状态。

这是当前设置,但不确定我缺少什么属性来使用 React Router 根据 URL 路径设置活动状态

数据导航

"navigation":[
        {
            "label":"Introduction",
            "path": "/"  
        },
        {
            "label":"Page Two",
            "path": "pagetwo"
        }
]
import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom';

const [selectedIndex, setSelectedIndex] = useState(0);

const handleListItemClick = (event, index) => {
   setSelectedIndex(index);
};

{data && data.navigation.map((item, i) =>
      <Link key={i} to={`${item.path}`} className={classes.link}> 
        <ListItem button selected={selectedIndex === i} onClick={(event) => handleListItemClick(event, i)}>
          <ListItemText className={classes.navLink}>{item.label}</ListItemText>
        </ListItem>
      </Link>
 )}

【问题讨论】:

  • 点击时handleListItemClickindex的值是多少?代码看起来不错。
  • 您想在哪里使用活动布尔值?您可以使用 NavLink 获取活动道具。
  • @jean182 布尔值可以设置一个当前用于设置所选导航链接样式的类。
  • @SanishJoseph - 索引是从data.navigation.map中提取的
  • 如果你只是想设置活动链接的一些样式,你为什么不试试 NavLink 呢?它有一个 ActiveClass 和你可以设置的活动样式属性。

标签: reactjs react-router react-router-dom


【解决方案1】:

如果您将每个链接都设为组件,则可以使用useRouteMatch,就像在the "custom link" example in the React Router docs 中一样。

function NavigationLink(props) {
  const match = useRouteMatch({
    to: props.path,
  });

  // update the link class to set styles appropriately depending
  // on whether active is true or false
  const classes = useStyles({ active: match != null });

  return (
    <Link to={props.path} className={classes.link}>
      <ListItem button selected={props.selected} onClick={props.onClick}>
        <ListItemText className={classes.navLink}>{props.children}</ListItemText>
      </ListItem>
    </Link>
  );
}

// In your existing component
data.navigation.map((item, i) => (
  <NavigationLink
    key={i}
    path={item.path}
    selected={selectedIndex === i}
    onClick={(event) => handleListItemClick(event, i)}
  >
    {item.label}
  </NavigationLink>
));

【讨论】:

  • 这似乎不起作用,而且我还收到 match 已定义但未使用的错误。
  • 哦,哈哈,我忘了实际使用match。您可能希望将其传递给 useStyles 并根据 match 是否为空来更新 link 类。我已经更新了我的答案。
【解决方案2】:

这是我为使其正常工作而设置的示例。我必须保持exact 才能正常工作。

https://stackblitz.com/edit/react-wvhugc?file=src/App.js

import React from 'react';
import './style.css';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink,
} from 'react-router-dom';
import ListItemText from '@mui/material/ListItemText';
import ListItem from '@mui/material/ListItem';

export default function App() {
  const navigation = [
    {
      label: 'Introduction',
      path: '/',
    },
    {
      label: 'Page Two',
      path: '/pagetwo',
    },
  ];
  return (
    <Router>
      {navigation.map((item, i) => (
        <NavLink
          exact
          activeStyle={{
            fontWeight: 'bold',
            color: 'red',
          }}
          key={i}
          to={`${item.path}`}
        >
          <ListItem button>
            <ListItemText>{item.label}</ListItemText>
          </ListItem>
        </NavLink>
      ))}
      <Switch>
        <Route exact path="/">
          <div>Home</div>
        </Route>
        <Route path="/">
          <div>Page 2</div>
        </Route>
      </Switch>
    </Router>
  );
}

【讨论】:

  • 可以将activeStyle 设置为一个类吗?我失去了以前设置当前选定链接样式的功能,但这是设置字体颜色。我怎样才能保留这个新功能,同时让它为焦点、活动和选定状态的链接设置样式?
  • 是的。 activeClassName="selected" 在该课程中给出你的风格。你可以用它代替activeStyle
  • 只需要为所选链接的类设置样式即可。谢谢!
猜你喜欢
  • 2020-10-02
  • 2017-09-24
  • 2016-07-01
  • 2017-06-22
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
相关资源
最近更新 更多