How to set activeClassName for wrapper element of Link or IndexLink in react-router?

前端 未结 10 1530
醉酒成梦
醉酒成梦 2020-12-07 15:56

I am new to the ReactJS world, and would like to know how can I pass active class name to the

  • element instead of (Link) element
  • 10条回答
    •  北荒
      北荒 (楼主)
      2020-12-07 16:23

      You need to enclose your

    • as a router aware component:

      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 (
            
    • {children}
    • ) } }

      Usage:

        Home A

      I took inspration from the react-router-bootstrap module, https://github.com/react-bootstrap/react-router-bootstrap/blob/master/src/LinkContainer.js. I didn't test it though so let me know how it goes.

    提交回复
    热议问题