【问题标题】:React Router v4 - active link issueReact Router v4 - 活动链接问题
【发布时间】:2018-09-05 13:23:10
【问题描述】:

我遇到了活动链接问题。 我需要创建一些子路由并在“父”路由上保持活动样式。我怎样才能做到这一点?

我使用 withRouter 进行路由。 假设我有 3 个“父”路由的主导航 - /login | /register /profile

 render () {
    return (
      <div className='grid'>
        <Route exact path='/' component={HomePage} />
        <Route path='/login' component={LoginForm} />
        <Route path='/register' component={RegisterForm} />
        <PrivateRoute path='/profile' component={PersonalDetails} />
        <PrivateRoute path='/profile/delete-account' component={DeleteAccount} />
        <PrivateRoute path='/profile/payments' component={Payments} />
        <PrivateRoute path='/profile/food-preferences' component={FoodPreferences} />
      </div>
    );
}

在“/profile”路径上呈现的组件内部有额外的导航,带有指向'/profile/delete-account/''/profile/payments''profile/food-preferences' 的链接。

static getProfileRoutes () {
    return profileRoutes.map(route => (
      <NavLink to={route.path} activeClassName='active-profile' className='profile-navigation-button' key={route.path}>
        <li className='profile-navigation-label'>{route.name}</li>
      </NavLink>
    ));
}

不幸的是,当我导航到“子”路线之一时,导航到 '/profile'SideBar 中按钮的活动样式丢失了。我该如何预防?修复它?

static getSideBarRoutes () {
    return sideBarRoutes.map(route => (
      <NavLink className='navigation-button' key={route.path} to={route.path}>
        <li className='navigation-item'>
          <div className={route.icon} />
          {route.name}
        </li>
      </NavLink>)
    );
}

路由工作得非常好——这只是active 类在Sidebar 上丢失的问题

非常感谢您的帮助。

【问题讨论】:

  • 你如何导航到父路由?如果你在那里使用exact,那就是个问题。
  • 你能解释一下吗? (我只是粘贴侧边栏导航代码)
  • 你没有使用它,所以这不是问题。嗯..当您单击“子”导航链接时,您会进入浏览器/父/子路由名称吗?
  • 是的,浏览器中有完整的路线名称。我只在默认路由“/”中使用“精确”
  • 尝试一些解决方法。在您创建“父”导航的组件中,做这样的事情。 if (props.location.pathname.indexOf(props.route) !== -1) { // here you can set parent active class if route contain parentRouteName in it. }

标签: css reactjs react-router


【解决方案1】:

例如

const navigation = (props) => {
  let styleClass= "not-active-class";
  if (props.location.pathname.indexOf(props.route) !== -1) {
    // checking if parent route is contained in route and setting active class
    styleClass= "active-class";
  }

  return (
    <NavLink
      to={props.route}
      activeClassName={styleClass} >
      <p>{props.route}</p>
    </NavLink>
  );
}

【讨论】:

  • 我会尝试这个解决方案,我会回复你。非常感谢您的参与。
猜你喜欢
  • 2017-08-02
  • 2017-06-22
  • 2017-08-31
  • 2017-04-29
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2022-11-22
相关资源
最近更新 更多