我有一个导航组件,呈现每个导航链接。此组件的返回如下所示:
return (
<li key={`nav-list-${el.title}-${index}`}>
<Link to={{pathname: '/c/' + el.urlkey}}
activeClassName={s.active}>{el.title}</Link>
{subNav}
</li>
);
活动类仅在页面刷新时设置。单击链接时,活动指示符将保留在初始链接中。
我没有使用 Redux,所以它似乎与此问题无关:单击链接时,activeClassName 在 sideMenu 上不起作用
我的路线看起来像这样:
<Route path="/c/:category(/:title)" component={CategoryView} name="category" />
使用 React-Router 2.8.1 和 browserHistory
7 回答
如果没有看到完整的代码就很难调试,但 React Router
activeClassName
的问题通常可以通过以下方式解决:IndexLink
:<li><IndexLink to="/" activeClassName="active">Home</IndexLink></li> <li><Link to="/" activeClassName="active">About</Link></li> <li><Link to="/" activeClassName="active">Contact</Link></li>
Links
上使用onlyActiveOnIndex
属性:<li><Link to="/" activeClassName="active" onlyActiveOnIndex>Home</Link></li> <li><Link to="/" activeClassName="active" onlyActiveOnIndex>About</Link></li> <li><Link to="/" activeClassName="active" onlyActiveOnIndex>Contact</Link></li>
这是第二个解决方案的工作演示:http://codepen.io/PiotrBerebecki/pen/qaKqRW
从ReactTraining为我做了
说明
使用
<NavLink>
而不是<Link>
并将 exact 添加为属性包含
exact
作为属性,以确保仅在与您的位置完全匹配的网址路径上触发activeClassName
例
资源
https://reacttraining.com/react-router/web/api/NavLink/exact-bool
如果为 true,则仅在位置完全匹配时才应用活动 class/style。
有同样的问题!通过
withRouter
包装父组件解决。 E.g。我不想升级,因为它导致的问题多于解决的问题。我没有使用 Redux 所以整个连接的东西都不适用。我尝试渲染纯粹和不纯(使用 pure-render 装饰器)没有结果。
所以我决定手动编写链接处理。我知道这超级详细,但它有效!
我添加了路由器上下文:
渲染返回:
点击处理程序如下所示:
最后我在渲染中设置了类:
有两个解决方案:
您可以升级到修复此问题的最新稳定版本
v3.0.0
(今天发布)。 (见https://github.com/ReactTraining/react-router/issues/3286#issuecomment-220861601)v2.8.1
https://stackoverflow.com/a/40126703编辑:您没有使用 Redux,因此第二个解决方案无效。
我在 react-router-dom v4.3 遇到了这个问题。我的整个应用程序已经使用 withRouter 包装。我也在使用 react-redux。我注意到它会将类添加到正确的链接。
我的导航链接看起来像这样