Active NavLink到父元素

Mos*_*she 15 reactjs react-router

我正在使用React Router v4,我有一个案例,在我的导航链接上,我想将activeclassName 启用到NavLink父元素,而不是NavLink自身.

有没有办法访问路径(match)即使我不在Switch元素内?

或者我必须保持状态?因为我觉得它有点缺少路由器的想法.

这是我的例子,我想将activeclassName应用于li元素而不是NavLink:

const {
  HashRouter,
  Switch,
  Route,
  Link,
  NavLink,
} = ReactRouterDOM

const About = () => (
    <article>
        My name is Moshe and I'm learning React and React Router v4.
    </article>
);

const Page = () => (
    <Switch>
      <Route exact path='/'  render={() => <h1>Welcome!</h1>} />
      <Route path='/about' component={About}/>
    </Switch>
);

const Nav = () => (
    <nav>
        <ul>
            <li><NavLink exact to="/">Home</NavLink></li>
            <li><NavLink to="/about">About</NavLink></li>
        </ul>
    </nav>
);

class App extends React.Component {
    render() {
        return (
            <div>
                <Nav />
                <Page />
            </div>
        );
    }
}
ReactDOM.render((
    <HashRouter>
        <App />
    </HashRouter>),
    document.querySelector("#app"));
Run Code Online (Sandbox Code Playgroud)

https://codepen.io/moshem/pen/ypzmQX

mar*_*kru 17

它似乎并不容易实现.我使用withRouter反应路由器文档中描述的HOC .它允许{ match, location, history }props位于Routess 外部的组件内部访问.在示例中,我将Nav组件包装为get location和它pathname.这是示例代码:

class Nav extends React.Component {
 getNavLinkClass = (path) => {
   return this.props.location.pathname === path ? 'active' : '';
 }
 render() {
  return (
    <nav>
      <ul>
        <li className={this.getNavLinkClass("/")}><NavLink exact to="/">Home</NavLink></li>
        <li className={this.getNavLinkClass("/about")}><NavLink to="/about">About</NavLink></li>
      </ul>
    </nav>
  )};
}
Nav = withRouter(Nav);
Run Code Online (Sandbox Code Playgroud)

您可能需要params在您的路线(如果有的话)中照顾,以便正确匹配.但是你仍然必须匹配你的每条路径NavLink,这可能不是漂亮的代码.但这个想法是,当路线改变时,重新Nav渲染并li突出显示正确.

这是codeandbox的一个工作示例.