Skip to main content

hierachy

React-router-dom 多级路由

main.jsx
import { HashRouter, Link, Switch, Route, Redirect } from "react-router-dom"
import styled from "styled-components"
import A from "./a"
import B from "./b"
const Layout = styled.div`
display: flex;
`

const LeftMenu = styled.nav`
padding: 20px;
height: 100vh;
box-sizing: border-box;
width: 20vw;
background: yellow;
display: flex;
flex-direction: column;

a {
margin: 4px 0;
}
`

const RightContent = styled.div`
background: pink;
width: 80vw;
`

const Main = () => {
return (
<HashRouter>
<Layout>
<LeftMenu>
<Link to="/a">/a</Link>
<Link to="/b">/b</Link>
</LeftMenu>
<RightContent>
<Switch>
{/* 匹配root */}
<Route path="/" exact component={A} />
<Route path="/a" component={A} />
<Route path="/b" component={B} />
{/* 其余走这个 */}
<Redirect to="/" />
</Switch>
</RightContent>
</Layout>
</HashRouter>
)
}
export default Main
a.jsx
import { Link } from "react-router-dom"
import styled from "styled-components"
import { Switch, Route, Redirect } from "react-router-dom"
import A1 from "./a1"
import A2 from "./a2"

const TopMenu = styled.nav`
background: purple;
padding: 20px 10px;

a {
color: #fff;
margin: 20px 10px;
}
`
export default function A() {
return (
<>
<TopMenu>
<Link to="/a/a1">a/a1</Link>
<Link to="/a/a2">a/a2</Link>
</TopMenu>
<Switch>
{/* 首页跳转到... */}
<Redirect exact from="/" to="/a/a1/" />
{/* 一级路由root跳转到... */}
<Redirect exact from="/a" to="/a/a1/" />
<Route path="/a/a1" component={A1} />
<Route path="/a/a2" component={A2} />
</Switch>
</>
)
}
a1.jsx
export default function A1() {
return (
<div
style={{
padding: 30,
fontSize: 30,
background: "red",
width: "100%"
}}
>
component A1
</div>
)
}
a2.jsx
export default function A2() {
return (
<div
style={{
padding: 30,
fontSize: 30,
background: "#33eeef",
width: "100%"
}}
>
component A2
</div>
)
}