0
使用react-router-dom
時,如何檢測用戶何時導航到新頁面?如何關閉更改路線的導航菜單
我目前使用的是"react-router-dom": "^4.2.2"
和"react": "^15.6.1"
。我想在用戶選擇新的目標網址時關閉手機導航菜單,但我無法檢測路由何時發生變化。
是否有回撥我可以掛鉤爲react-router-dom
?我想能夠沿着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>
截圖:
謝謝gravityplanx。我如何調整您的示例以適應以下情況? a)如果點擊我當前頁面的鏈接,則不會發生URL更改,因此我希望菜單保持打開狀態並b。)如果單擊頁面上其他位置的鏈接,我的URL會更改,所以我希望導航菜單關閉。 –
a)使用react-router的['activeStyle']組合(https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md# activestyle-object)屬性以及css屬性['pointer-events'](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) – gravityplanx