javascript - 如何在 react-router 中为 Link 或 IndexLink 的包装元素设置 activeClassName?

标签 javascript reactjs react-router redux

我是 ReactJS 世界的新手,想知道如何将事件类名传递给 <li>元素而不是 <a>(Link)元素。

现在我有了这样的代码。单击时 anchor 类会发生变化。

<li><IndexLink to='/' activeclassName='active'>A</IndexLink></li>
<li><Link to='/b' activeclassName='active'>B</Link></li>
<li><Link to='/c' activeclassName='active'>C</Link></li>

但我想得到类似的东西:

<li activeclassName='active'><IndexLink to='/'>A</IndexLink></li>
<li activeclassName='active'><Link to='/b'>B</Link></li>
<li activeclassName='active'><Link to='/c'>C</Link></li>

提前致谢

最佳答案

您需要附上您的 <li>作为路由器感知组件:

import { Link, IndexLink } from 'react-router'

class NavItem extends React.Component {
  render () {
    const { router } = this.context
    const { index, onlyActiveOnIndex, to, children, ...props } = this.props

    const isActive = router.isActive(to, onlyActiveOnIndex)
    const LinkComponent = index ? Link : IndexLink

    return (
      <li className={isActive ? 'active' : ''}>
        <LinkComponent {...props}>{children}</LinkComponent>
      </li>
    )
  }
}

用法:

<ul>
  <NavItem to='/' index={true}>Home</NavItem>
  <NavItem to='/a'>A</NavItem>
</ul>

我从 react-router-bootstrap 模块中获得灵感,https://github.com/react-bootstrap/react-router-bootstrap/blob/master/src/LinkContainer.js .我没有测试它,所以让我知道它是怎么回事。

关于javascript - 如何在 react-router 中为 Link 或 IndexLink 的包装元素设置 activeClassName?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053161/

相关文章:

javascript - onclick ="location.href=' link.html'"在 Safari 中不加载页面

reactjs - 使用 Enzyme 测试窗口滚动事件处理程序的最佳方法是什么?

javascript - 在路由器路由上 react 无限循环

javascript - 落在位置上。纯 Javascript/HTML5

javascript - 输入图像源并即时显示

javascript - 是否可以从 xpath 节点更改 css?

express - 使用react-router和expressroutes.js有什么区别

javascript - react-router setRouteLeaveHook 仍在更新 URL

java - dropwizard 应用程序中的配置更改以与 React browserHistory 配合使用

reactjs - Jest 测试 React Router Prompt