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

前端 未结 10 1511
醉酒成梦
醉酒成梦 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

      Using react 15.1.0, react-router 2.5.0 and bootstrap 3.3 (this is less important), I developed this solution for making the links active:

      npm install --save classnames

      npm install --save lodash

      The component:

      import React from 'react';
      import { Link, IndexLink } from 'react-router';
      import _ from 'lodash';
      import classnames from 'classnames';
      
      class NavItem extends React.Component {
        constructor(props) {
          super(props);
      
          // The default state
          this.state = {
            isActive: false,
            unregisterRouteListener: false
          };
      
          // Binding for functions
          this.locationHasChanged = this.locationHasChanged.bind(this);
        }
      
        componentDidMount() {
          // Check if component is active on mount and add listener on route change
          this.setState({
            isActive: this.context.router.isActive(this.props.to, true),
            unregisterRouteListener: this.context.router.listen(this.locationHasChanged)
          });
        }
      
        componentWillUnmount() {
          if (this.state.unregisterRouteListener) {
            // Remove the listener
            this.state.unregisterRouteListener();
          }
      
          // Reset the state
          this.setState({
            isActive: false,
            unregisterRouteListener: false
          });
        }
      
        // Update the state of the component, based on the router path
        locationHasChanged() {
          this.setState({
            isActive: this.context.router.isActive(this.props.to, true)
          });
        }
      
        render () {
          let { index } = this.props;
          let LinkComponent = index ? Link : IndexLink;
          let newProps = _.omit(this.props, 'router');
      
          return (
            
    • {this.props.children}
    • ); } } NavItem.contextTypes = { router: React.PropTypes.object }; export default NavItem;

      Usage:

      List
      

      I am a beginner with React, so the above solution surely needs improvements and might contain approach errors. However, it might also contain useful information or a starting point to those interested.

      Any feedback or suggestions are more than welcome. Thanks! :)

    提交回复
    热议问题