我正在尝试向仪表板布局内导航组件内的活动路径添加自定义样式,但是我无法在当前组件内获取当前路径。
const Index = props => {
return (
<BrowserRouter>
<DashboardLayout>
<Route exact path='/' component={Dashboard} />
<Route exact path='/earnings' component={Earnings} />
<Route exact path='/comms' component={Comms} />
<Route exact path='/rankings' component={Rankings} />
<Route exact path='/ratings' component={Ratings} />
<Route exact path='/ads' component={Ads} />
<Route exact path='/settings' component={Settings} />
<Route exact path='/ad/details' component={AdDetails} />
<Route exact path='/ad/submit-sample' component={SubmitSample} />
<Route exact path='/feedback' component={Feedback} />
</DashboardLayout>
</BrowserRouter>
);
};
export default Index;
答案 0 :(得分:0)
我制作了一个看起来像这样的小组件:
import React from 'react';
import { Route, Link } from 'react-router-dom';
const Nav = ({
children,
to,
exact,
onClick,
className,
...rest
}) => (
<Route
path={to}
exact={exact}
children={({ match }) => (
<Link
// Assign class and active class name
className={match ? `${className} act-link` : className}
to={to}
replace={match && to === match.path}
onClick={(e) => {
// Avoid clicking the current route
if (!match || to !== match.path) {
onClick(e);
}
}}
{...rest}
>
{children}
</Link>
)}
/>
);
您可以通过以下方式使用它:
const NavList = ({
links,
toggleOpened,
}) => (
<ul className="main-menu">
{
links.map((link) => (
<li
key={link.name}
className={link.className}
>
<NavLink
className="icon-w"
to={link.url}
onClick={(e) => {
e.target.focus();
toggleOpened(false);
}}
>
<div className={`os-icon ${link.icon}`} />
</NavLink>
</li>
))
}
</ul>
);
希望有帮助