我在使用React Router时遇到了一个奇怪的问题。仅当我从'/'导航到子组件时,activeClassName才会生效。但是,如果我尝试从“更新”导航到“更新密码”,它将无效。它会将活动类保持在更新视图中,反之亦然,它取决于我从'/'导航后首先命中的路径。请看下面的代码:
我如何定义路线
<Provider store={store}>
<Router history={hashHistory}>
<Route path="/" component={ Template } >
<IndexRoute component={ Welcome } />
<Route path="login" component={ Login } />
<Route path="register" component={ Register } />
<Route onEnter={requireLogin}>
<Route path="update" component={ Update } />
<Route path="updatepassword" component={ Update_password } />
</Route>
</Route>
</Router>
</Provider>
链接:
<nav className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<Link to={ '/' } className="navbar-brand">React-Phoenix-Chat</Link>
</div>
<div className="collapse navbar-collapse" id="navbar">
<ul className="nav navbar-nav navbar-right">
<li> <a onClick={this.handleLogout.bind(this)} href="#" activeClassName="active">Logout</a></li>
<li><Link activeClassName="active" to={ 'update' }>Update</Link></li>
<li><Link activeClassName="active" to={ 'updatepassword' }>Update Password</Link></li>
<li><a href="#">{this.props.user.username}</a></li>
</ul>
</div>
</div>
</nav>
答案 0 :(得分:1)
我发现了问题。我不得不改变这个:
<Route onEnter={requireLogin}>
<Route path="/update" component={ Update } />
<Route path="/updatepassword" component={ Update_password } />
</Route>
对此:
<Route path="/update" component={ Update } onEnter={requireLogin} />
<Route path="/updatepassword" component={ Update_password } onEnter={requireLogin} />