我们如何将父li className更改为在点击的路线上处于活动状态, 任何帮助将不胜感激
问题在于li是ROUTER-> LINK的父级
import React, {Component} from 'react';
import {
BrowserRouter as Router,
Link,
Route,
Switch,
} from 'react-router-dom';
class Header extends Component {
render() {
return(
<header className="nk-header nk-header-opaque">
<nav className="nk-navbar nk-navbar-top nk-navbar-sticky nk-navbar-transparent nk-navbar-autohide">
<div className="container">
<div className="nk-nav-table">
<a href="index.html" className="nk-nav-logo">
<img src="assets/images/logo.png" alt="" width="90" />
</a>
<ul className="nk-nav nk-nav-right hidden-md-down" data-nav-mobile="#nk-nav-mobile">
<li className="active">
<Link to="/" activeClassName="active">Home</Link>
</li>
<li className=" ">
<Link to="/Product" activeClassName="active">Product</Link>
</li>
</ul>
</div>
</div>
</nav>
</header>
);
}
}
export default Header;
答案 0 :(得分:3)
首先,最好构造菜单项的JSON obj
const modules : [
{
id : 1,
name : 'Home',
linkTo : '/',
},
{
id : 2,
name : 'Product',
linkTo : '/product',
}
]
现在,在渲染方法中获取请求的路径名
let requestedPath = this.context.router.route.location.pathname;
现在,渲染菜单项
return(
<header className="nk-header nk-header-opaque">
<nav className="nk-navbar nk-navbar-top nk-navbar-sticky nk-navbar-transparent nk-navbar-autohide">
<div className="container">
<div className="nk-nav-table">
<a href="index.html" className="nk-nav-logo">
<img src="assets/images/logo.png" alt="" width="90" />
</a>
<ul className="nk-nav nk-nav-right hidden-md-down" data-nav-mobile="#nk-nav-mobile">
{modules.map((module, index) => {
let className = module.linkTo === requestedPath ? 'active' : '';
return (
<li className="active" key={index}>
<Link to={module.linkTo} className={className}>{module.name}</Link>
</li>
)
})}
</ul>
</div>
</div>
</nav>
</header>
);
注意:我没有编译代码。
答案 1 :(得分:0)
在渲染器中添加它
const activeClass = (route) => { return location.pathname === route ? "active" : null }
李应该是这个:
<li className={activeClass("/")}>
<Link to="/">Home</Link>
</li>
<li className={activeClass("/Product")}>
<Link to="/Product">Product</Link>
</li>