【发布时间】: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