我是ReactJS领域的新手,想知道如何将活动类名传递给<li>元素而不是<a>(Link)元素.

现在我有了这种代码.单击时,锚定类会发生更改.

<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路由 bootstrap 模块https://github.com/react-bootstrap/react-router-bootstrap/blob/master/src/LinkContainer.js中获取了信息.但我没有测试,所以请告诉我进展如何.

Reactjs相关问答推荐

安装后未渲染tailwind

For循环中的元素在Reaction中丢失挂钩

Redux Provider Stuck甚至彻底遵循了文档

如何在React中的textarea中显示字符数?

获取点击的国家/地区名称react 映射

for each 子级加载父路由加载器

安装使用环境的BIT组件的依赖项

我在Route组件上使用元素属性,这样就不需要ID了吗?

当我无法引用模态组件时,如何使模态组件在 Next.js/React 中管理自己的状态?

React中的功能性组件克隆优化

为什么这个 React 组件会导致无限渲染?

运行 npm run build 出现问题

根据其中的值不同地react setState 更新状态

在 React JS 中编辑表格数据

从服务器获取数据时未定义,错误非法调用

如何使用 React Hook Form 将寄存器作为 props 发送到子组件来收集数据?

当从数组中删除数据时,UseEffect 不会重新渲染,仅在添加数据时才会重新渲染

在 Reactjs 中状态发生变化时渲染一个新组件而不替换旧组件

无法重用我的组件,它只显示 1 次

单击按钮时获取react 表中每一行的属性