Get an active route with react-router in ReactJs

痞子三分冷 提交于 2019-12-05 15:24:27

问题


I am creating a project using reactjs.In my application i am getting the active route using this:

this.context.router.isActive

but getting undefined, i am using the react-router 4.Earlier this was worked for me when am using the lower version of react-router. Here is my code:

class NavLink extends React.Component {

    render() {


     console.log( this.context.router.isActive)
          let isActive = this.context.router.isActive(this.props.to, true);
           let className = isActive ? "active" : "";
        return(
            <li  className={className} {...this.props}>
               <Link {...this.props}/>
            </li >
        );
    }
}

NavLink.contextTypes = {
    router: PropTypes.object
};

回答1:


The architecture has changed in react-router v4 and this.context.router.isActive is no longer supported.

In react-router-v4, you could instead of creating a NavLink yourself use the exposed NavLink component.

From the documentation:

NavLink

A special version of the that will add styling attributes to the rendered element when it matches the current URL.

import { NavLink } from 'react-router-dom'

<NavLink to="/about">About</NavLink>

It also provides you an activeClassName prop:

activeClassName: string

The class to give the element when it is active. The default given class is active. This will be joined with the className prop.

<NavLink
  to="/faq"
  activeClassName="selected"
>FAQs</NavLink>

Why is this.context.router.isActive not supported:

Here is an excerpt from a github issue

Rendering a <Route> does not necessarily mean "only render when you match the current location". For example, it can be used inject the router variables from the context into a component as props.

In <NavLink>, the <Route> is using the children prop, which means that it will call the children function whether or not the route matches. If the match is null, then we know that it did not match.

If you would prefer not to use <Route children> in this way, React Router offers an imperative approach with the matchPath function. This is what <Switch>es and <Route>s use internally to match a location against a path.

If your component is not receiving the Router props, then you could inject it using the withRouter HOC

import { withRouter } from 'react-router';

export class withRouter(MyComponent);


来源:https://stackoverflow.com/questions/47693540/get-an-active-route-with-react-router-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!