react的router二级路由
时间: 2023-07-23 18:08:47 浏览: 53
React Router 是 React 提供的用于处理路由的库,支持创建多级嵌套的路由结构。对于二级路由,可以在父级路由组件中定义子级路由,并在子级路由组件中渲染对应的内容。
下面是一个使用 React Router 实现二级路由的示例:
```jsx
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// 父级路由组件
const ParentComponent = () => {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</Router>
);
};
// 子级路由组件
const Dashboard = () => {
return (
<div>
<h2>Dashboard</h2>
<Router>
<Switch>
<Route exact path="/dashboard/profile" component={Profile} />
<Route exact path="/dashboard/settings" component={Settings} />
</Switch>
</Router>
</div>
);
};
// 其他组件
const Home = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;
const Profile = () => <h3>Profile</h3>;
const Settings = () => <h3>Settings</h3>;
```
在上面的示例中,`ParentComponent` 是父级路由组件,它定义了根路径 `/`、`/about` 和 `/dashboard` 的路由。其中,`/dashboard` 路由对应的组件是 `Dashboard`,它又定义了 `/dashboard/profile` 和 `/dashboard/settings` 的子级路由。
子级路由组件 `Dashboard` 中也使用了 `Router` 组件来定义自己的路由规则。这样,当访问 `/dashboard/profile` 或 `/dashboard/settings` 时,React Router 会根据路由规则渲染对应的组件。
以上就是使用 React Router 实现二级路由的简单示例。希望能对你有所帮助!