【问题标题】:Get an active route with react-router in ReactJs在 ReactJs 中使用 react-router 获取活动路由
【发布时间】:2018-05-21 11:17:42
【问题描述】:

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

this.context.router.isActive

但未定义,我正在使用 react-router 4. 之前,当我使用较低版本的 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
};

【问题讨论】:

    标签: javascript reactjs react-router react-router-v4


    【解决方案1】:

    react-router v4 中的架构发生了变化,不再支持this.context.router.isActive

    在 react-router-v4 中,您可以使用暴露的 NavLink 组件来代替自己创建 NavLink。

    From the documentation:

    导航链接

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

    import { NavLink } from 'react-router-dom'
    
    <NavLink to="/about">About</NavLink>
    

    它还为您提供了一个 activeClassName 属性:

    activeClassName:字符串

    当元素处于活动状态时赋予该元素的类。给定的默认值 课堂活跃。这将与 className 属性连接。

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

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

    这是 github 问题的摘录

    渲染&lt;Route&gt; 并不一定意味着“仅在匹配当前位置时渲染”。例如,它可以用于将上下文中的路由器变量作为 props 注入到组件中。

    &lt;NavLink&gt; 中,&lt;Route&gt; 使用了 children 属性,这意味着无论路由是否匹配,它都会调用 children 函数。如果匹配为空,那么我们就知道它不匹配。

    如果您不想以这种方式使用&lt;Route children&gt;,React Router 提供了一种带有matchPath 函数的命令式方法。这就是 &lt;Switch&gt;es&lt;Route&gt;s 在内部使用来将位置与路径匹配。

    如果您的组件没有收到 Router 属性,那么您可以使用 withRouter HOC 注入它

    import { withRouter } from 'react-router';
    
    export class withRouter(MyComponent);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-02
      • 2017-01-15
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2016-11-11
      • 2018-12-25
      • 1970-01-01
      相关资源
      最近更新 更多