所以我正在制作一个网站,我为我的导航链接制作了一个移动抽屉,当我单击包含 3 行的按钮并关闭它时,它打开正常我做了一个背景,但现在当我单击链接转到下一页时,导航抽屉没有关闭,要关闭它,我必须点击背景屏幕,我希望抽屉在我关闭时关闭单击页面链接。
app.js
state = {
sideDrawerOpen: false
};
drawerToggleClickHandler = () => {
this.setState((prevState) => {
return { sideDrawerOpen: !prevState.sideDrawerOpen };
});
};
backdropClickHandler = () => {
this.setState({ sideDrawerOpen: false });
};
render() {
let backdrop
if (this.state.sideDrawerOpen) {
backdrop = <Backdrop click={this.backdropClickHandler} />
}
return (
<Router>
<div className="App">
<div style={{ height: '100%' }}>
<Toolbar drawerClickHandler={this.drawerToggleClickHandler} />
<SideDrawer show={this.state.sideDrawerOpen} />
{backdrop}
<Route exact path='/' component={Home} />
<Route exact path='/Contact' component={Contact} />
<Route exact path='/Events' component={Events} />
<Route exact path='/About' component={About} />
<Route exact path='/Gallery' component={Gallery} />
</div>
</div>
</Router>
drawer.js
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/About">About</Link></li>
<li><Link to="/Events">Events</Link></li>
<li><Link to="/Gallery">Gallery</Link></li>
<li><Link to="/Contact">Contact</Link></li>
</ul>
</nav>
您的<Router>
以app.js
的形式呈现在组件内部,因此更改页面不会触发卸载或重置状态。但是,您可以在componentDidUpdate
中检测到页面更改,并使用它来手动关闭抽屉:
componentDidUpdate(prevProps) {
const { location } = this.props;
if (location !== prevProps.location && this.state.sideDrawerOpen) {
this.setState({ sideDrawerOpen: false });
}
}
延伸阅读:https://reacttraining.com/react-router/web/api/history/history-is-mutable