[英]React router dom set active class to the NavLink
I am using React-router-dom for navigation我正在使用 React-router-dom 进行导航
Routes.js路由.js
<Router>
<Switch>
<Route path="/" exact component={HomePage} activeClassName="routeActive"/>
<Route path="/login" exact component={Login} activeClassName="routeActive"/>
<Route path="/category/veg" exact component={Veg} activeClassName="routeActive"/>
<Route path="/category/non-veg" exact component={NonVeg} activeClassName="routeActive"/>
</Switch>
</Router>
then in my Navbar component i have然后在我的导航栏组件中
<div className="leftNavItems">
<ul className="navItemsUL">
<li className="navItemsLI">
<NavLink to="/" exact className="linkText" activeClassName="routeActive">
Home
</NavLink>
</li>
<li className="navItemsLI">
<NavLink to="/login" exact className="linkText" activeClassName="routeActive">
About us
</NavLink>
</li>
<div className="dropdown">
{console.log(props)}
{props.location}
<span className={` linkText`}>Categories </span>
<i className="fas fa-caret-down downIcon" />
<div className="dropdownContent">
<ul className="dropdownContentUL">
<li className="dropdownContentLI">
<Link to="/category/:veg" className="dropdownLinkText">
Veg
</Link>
</li>
<li className="dropdownContentLI">
<Link to="/category/:non-veg" className="dropdownLinkText">
Non Veg
</Link>
</li>
</ul>
</div>
</div>
</ul>
</div>
so as u can see i have used "activeClassName" for the Navlink to set className and then change its color if it is active but there is a case where i have a label "Category" which has a dropdown menu that contains for "veg" and "non-veg", so what i want is also need to change the color of "Category" label when the user is in either /category/veg or /caegory/:non-veg as it is Navbar Component console.log(props.location) is undefined over here bacause it is not insise i suppose.如您所见,我已经为 Navlink 使用“activeClassName”来设置类名,然后在它处于活动状态时更改其颜色,但在某些情况下,我有一个 label “Category”,它有一个包含“veg”的下拉菜单和“非蔬菜”,所以我想要的还需要更改“类别”label 的颜色,因为它是导航栏组件控制台.log( props.location) 在这里是未定义的,因为我认为它不是 insise。 Any other way around here >
这里有任何其他方式>
first, about console.log(props.location)
turns to undefined
, are you sure you wrapped the component with withRouter
?首先,关于
console.log(props.location)
变成undefined
,你确定你用withRouter
包裹了组件吗? also if it is a function component you can use the hook let location = useLocation()
另外,如果它是 function 组件,您可以使用钩子
let location = useLocation()
second, you can control the class name manually like其次,您可以手动控制 class 名称,如
<span className={`${props.location.pathname.split('/').includes('category') ? 'routeActive' : 'linkText' }`}>Categories </span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.