在嵌套路由中保持初始路由活动 - React Router

时间:2016-06-25 09:33:12

标签: reactjs react-router

我的路线设置如下:

<Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="elements" component={Elements}>
        <Route path="buttons" component={ElementsButtons}/>
    </Route>
    <Route path="design" component={Design}/>
</Route>

HTML

<DropElement to="/elements">Elements</DropElement>
    <ul className="dropElement-list">
        <NavLink to="/elements/tables">Container</NavLink>
        <NavLink to="/elements/buttons">Buttons</NavLink>
...

DropElement

export default React.createClass({
    contextTypes: {
             router: React.PropTypes.object
     },

     render: function () {
             let isActive = this.context.router.isActive(this.props.to, true),
                     className = isActive ? "active dropElement" : "dropElement";

             return (
                     <li className={className}>
                             <Link {...this.props}>
                                     {this.props.children}
                             </Link>
                     </li>
             );
     }
   })

NavLink

export default React.createClass({
     render: function () {
             return (
                 <li>
                     <Link {...this.props}>
                             {this.props.children}
                     </Link>
                    </li>
             );
     }
})

当我访问 / elements 时,此功能正常。我的问题是,如何将活跃的课程保持在&#39; Elements&#39;我导航到 / elements / buttons

1 个答案:

答案 0 :(得分:1)

传递给isActive的第二个参数告诉函数只有在第一个参数与确切路径匹配时才返回true。

所以

let isActive = this.context.router.isActive(this.props.to, true)

应该是

let isActive = this.context.router.isActive(this.props.to)

isActive documentation