问题 在ReactJs中使用react-router获取活动路由


我正在使用reactjs创建一个项目。在我的应用程序中,我使用以下方法获取活动路径:

this.context.router.isActive

但是未定义,我正在使用react-router 4.Earlier当我使用较低版本的react-router时,这对我有用。 这是我的代码:

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
};

4230
2017-12-07 11:00


起源



答案:


这个架构在react-router v4和 this.context.router.isActive 不再受支持。

在react-router-v4中,您可以自己使用暴露而不是创建NavLink NavLink 零件。

从文档:

NavLink

一个特殊版本,它将添加样式属性   与当前URL匹配时的呈现元素。

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

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

它还为您提供了activeClassName prop:

activeClassName:string

在活动时为元素提供的类。默认给定   班是活跃的。这将与className prop一起加入。

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

为什么不支持this.context.router.isActive:

这是一段摘录 github上 问题

渲染一个 <Route> 并不一定意味着“只在匹配当前位置时才呈现”。例如,它可以用于将来自上下文的路由器变量作为props注入到组件中。

<NavLink><Route> 正在使用子prop,这意味着它将调用子函数,无论路由是否匹配。如果匹配为null,那么我们知道它不匹配。

如果你不想使用 <Route children> 通过这种方式,React Router提供了一种必要的方法 matchPath 功能。这是什么 <Switch>es 和 <Route>s 内部使用以匹配路径的位置。

如果您的组件没有收到 Router 道具,然后你可以用它注入它 withRouter HOC

import { withRouter } from 'react-router';

export class withRouter(MyComponent);

14
2017-12-12 06:52