如何在路线更改时关闭导航菜单 [英] How to Close Navigation Menu on Route Change

查看:44
本文介绍了如何在路线更改时关闭导航菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 react-router-dom,如何检测用户何时导航到新页面?

With react-router-dom, how can I detect when the user navigates to a new page?

我目前正在使用 "react-router-dom": "^4.2.2""react": "^15.6.1".我想在用户选择新的目标 URL 时关闭我的移动导航菜单,但我无法检测到路由何时更改.

I'm currently using "react-router-dom": "^4.2.2" and "react": "^15.6.1". I want to close my mobile navigation menu when the user has selected a new target URL, but I'm having trouble detecting when the route has changed.

是否有我可以为 react-router-dom 挂钩的回调?我希望能够沿着 location.onChange(() => { this.state.collapsed = true; })

Is there a callback I can hook into for react-router-dom? I would like to be able to call code along the lines of location.onChange(() => { this.state.collapsed = true; })

我目前的代码如下:

组件:

class Leftnav extends Component {

 constructor() {
    super();
    this.state = {
      collapsed: true,
    };
  }

  toggleMenu = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    })
  };

  render() { ... { */html here/* } ... };
};

模板:

<ul className={"leftnav-collapse " + (this.state.collapsed ? 'collapsed' : '')}>
    <li><NavLink to={`/events`} activeClassName="current">Events</NavLink></li>
    <li><NavLink to={`/people`} activeClassName="current">People</NavLink></li>
</ul>

截图:

推荐答案

<NavLink to={`/events`} 
         activeClassName="current"
         onClick={this.toggleMenu}
    >Events</NavLink>

您可能还需要更新 toggleMenu 函数以防止默认点击操作,因为点击处理程序已应用.

You may need to also update the toggleMenu function to prevent the default click action, now that a click handler is applied.

toggleMenu = (e) => {
    if (e) {
        e.preventDefault();
    }
    this.setState({collapsed: !this.state.collapsed});
}

这篇关于如何在路线更改时关闭导航菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆