如何在使用react router dom单击链接后隐藏菜单



我想要一个网站菜单,但在它将我重定向到正确的页面后,我希望菜单消失。我设法使用如下所述的反应路由器dom和useLocation来实现它,但我真的觉得有更好的方法,因为我不喜欢用"/"作为常数。。。有谁有更好的主意吗?

import React from "react";
import styled from "styled-components";
import {get} from 'lodash'
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useLocation
} from "react-router-dom";

const MenuWrapper = (props) => {
let location = useLocation()
if (get(location, 'pathname') === '/') {
return (<div className={props.className}>{props.children}</div>)
} else {
return null
}
}
const Page = styled.div`
`
const MenuBox = styled(MenuWrapper)`
`;
const MenuButton = styled(Link)`
`;
export default function Home() {
return (
<Page>
<Router>
<MenuBox>
<MenuButton to={'/someURL'}>play against computer</MenuButton>
<MenuButton to={'/home'}>Home</MenuButton>
</MenuBox>
<Switch>
<Route path={'/someURL'}><PlayRandomMoveEngine/></Route>
<Route path={'/home'}>
<div/>
</Route>
</Switch>
</Router>
</Page>
);
}

您可以尝试将MenuBox插入应用程序的其他方法。按照下面的代码

const Router = () {
return (
<Page>
<Router>
<Switch>
<Route path="/" exact>
<HomePage>
</Route>
<Route path="/someURL">
<PlayRandomMoveEngine/>
</Route>
</Switch>
</Router>
</Page>
);
}

主页.js

import MenuBox from '~/components/MenuBox';
const HomePage = () => {
return (
<>
<MenuBox>
<MenuButton to="/someURL">play against computer</MenuButton>
<MenuButton to={'/home'}>Home</MenuButton>
</MenuBox>
<div> HOME PAGE ! </div>
</>
)
}

因此,您将只能通过下一个路径"/"看到MenuBox。如果您决定在其他页面上显示带有其他菜单项的菜单,这不是问题。只需导入MenuBox,它就会很好地工作

最新更新