React Router V5实现嵌套路由

1,585 阅读1分钟
  1. 配置一级路由结构
import React from "react";
import { Link, Route, Switch, Redirect } from "react-router-dom";
import Child1 from "./components/Child1";
import Child2 from "./components/Child2";
function App() {
  return (
    <div>
      <div>
        {/* link 导航 */}
        {/* 也使用 NavLink,相比link 它多了一个点击时的 active 类,可以设置点击时样式 */}
        <Link to="/child1">Link: go to child1</Link> |{" "}
        <Link to="/child2">Link: go to child2</Link>
      </div>
      <div>
        {/* 定义路由出口 */}
        <Switch>
          {/* 根组件默认展示,要添加 exact 属性,防止二次渲染 */}
          {/* <Route path="/" component={Child1} exact />*/}
          {/* 路由重定向 */}
          <Redirect from="/" to="/child1/child1A" exact />

          <Route path="/child1" component={Child1} />
          <Route path="/child2" component={Child2} />
        </Switch>
      </div>
    </div>
  );
}

export default App;
  1. 配置子路由结构 在 Child1.js 中,link,Route 标签中要写全路径
import React, { Component } from "react";
import { Link, Route, Switch } from "react-router-dom";
import Child1A from "./Child1A";
import Child1B from "./Child1B";

export default class Child1 extends Component {
  render() {
    return (
      <>
        <div>
          <Link to="/child1/child1A">Link: go to child1A</Link> |{" "}
          <Link to="/child1/child1B">Link: go to child1B</Link>
        </div>
        <div>
          <Switch>
            <Route path="/child1/child1A" component={Child1A} />
            <Route path="/child1/child1B" component={Child1B} />
          </Switch>
        </div>
      </>
    );
  }
}

参考链接:events.jianshu.io/p/8d3334b4c…