React router <NavLink> with active style doesn't work as I required with root URL

半世苍凉 提交于 2019-12-10 13:47:09

问题


I used this NavLinks in the main menu. The issue is that when '/Test/car' link is clicked '/Test' link is also applying the styles. I believe it's because '/Test' suppose to be the root of other links. so it make sense.

But I want '/Test' link also to work like other links when applying the active style. So '/Test' will get applied the styles only when that 'Home' link is clicked. How I get that done (in a reactjs way)?

<Route exact path="/TEST" component={Home}></Route>
<Route path="/TEST/car" component={Car}></Route>
<Route path="/TEST/van" component={Van}></Route>
<Route path="/TEST/train" component={Train}></Route>

<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST" onClick={this.closeMenuForMobile.bind(this)} >Home</NavLink>
<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST/car" onClick={this.closeMenuForMobile.bind(this)} >Car</NavLink>
<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST/van"  onClick={this.closeMenuForMobile.bind(this)} >Van</NavLink>
<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST/train" onClick={this.closeMenuForMobile.bind(this)}>Train</NavLink>

回答1:


Just like your path use exact

Change this

<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} to="/TEST" onClick={this.closeMenuForMobile.bind(this)} >Home</NavLink>

To this

<NavLink activeStyle={{borderBottom: 'solid 3px #fff', paddingBottom: '1em'}} exact to="/TEST" onClick={this.closeMenuForMobile.bind(this)} >Home</NavLink>

Source: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md#exact-bool



来源:https://stackoverflow.com/questions/45158135/react-router-navlink-with-active-style-doesnt-work-as-i-required-with-root-ur

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