天天看点

项目中嵌套路由

布局图片如下所示:

可见项的的布局:

分为两大类:1、home页面里,还有路由跳转;2、cityle页面里没有路由跳转了

项目中嵌套路由

总的:

// import { Button } from 'antd-mobile';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from "./pages/Home";
import CityList from "./pages/CityList";
function App() {
  return (
    <Router>
      <div className="App">
        <Link to="/home">首页</Link>
        <Link to="/citylist">城市选择</Link>
        <Route path="/home" component={Home}></Route>
        <Route path="/citylist" component={CityList}></Route>
      </div>
    </Router>
  );
}
export default App;      

cityle页面:

import React from 'react';
class CityList extends React.Component {
  render() {
      return (<div>这是citylist组件</div>)
  }
}
export default  CityList;      

home页面:

import React from 'react';
import { Route } from "react-router-dom";
import News from '../News/index';
class Home extends React.Component {
    render() {
        return (<div>
            <div>这是home组件</div>
            <Route path="/home/news" component={News}></Route>
        </div>)
    }
  }
  export default  Home;      

home页面里的路由出口:

import React from "react";
class News extends React.Component {
    render() {
        return (<div>这是news组件</div>)
    }
  }
  export default  News;      

使用步骤:

  1. 在 pages 文件夹中创建 News/index.js组件
  2. 在 Home 组件中,添加一个Route 作为子路由(嵌套的路由)的出口
  3. 设置嵌套路由的path,格式以父路由 path 开头(父组件展示,子组件才会展示)
  4. 修改 pathname 为 /home/news,News 组件的内容就会展示在Home 组件中
<Router> <div> <Route path="/home" component={Home} /> </div> </Router>


const Home = () => ( <div> <Route path="/home/news" component={News} /> </div> )