gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:04:27 28 4
gpt4 key购买 nike

我是 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com