1. 1.首先需要定义两个子路由组件
    2. 2.在父组件中引入两个定义好的组件
    3. 3.通过link标签实现导航
    4. 4switch定义路由组件,匹配对应路由组件
    5. 5.这里的匹配路劲需要带上父组件的路由路径
    6. 6.重定向路由组件,使得初始页面时路由组件可以默认渲染

    父组件

    1. import React, { Component } from 'react'
    2. import {Link,Route,Switch,Redirect} from 'react-router-dom'
    3. import Message from './Message'
    4. import News from './News'
    5. import "./index.css"
    6. export default class Index extends Component {
    7. render() {
    8. return (
    9. <div>
    10. <h1>我是home组件</h1>
    11. <ul className="navList">
    12. <li>
    13. <Link to="/home/message">消息组件</Link>
    14. </li>
    15. <li>
    16. <Link to="/home/news">新闻组件</Link>
    17. </li>
    18. </ul>
    19. <div>
    20. <Switch>
    21. <Route path="/home/message" component={Message}></Route>
    22. <Route path="/home/news" component={News}></Route>
    23. <Redirect to="/home/news"></Redirect>
    24. </Switch>
    25. </div>
    26. </div>
    27. )
    28. }
    29. }

    路由子组件

    1. //Message.jsx
    2. import React, { Component } from 'react'
    3. import "./index.css"
    4. export default class index extends Component {
    5. render() {
    6. return (
    7. <div>
    8. <ul className="messageList">
    9. <li>我是消息组件1</li>
    10. <li>我是消息组件2</li>
    11. <li>我是消息组件3</li>
    12. <li>我是消息组件4</li>
    13. <li>我是消息组件5</li>
    14. <li>我是消息组件6</li>
    15. </ul>
    16. </div>
    17. )
    18. }
    19. }
    20. //News.jsx
    21. import React, { Component } from 'react'
    22. import "./index.css"
    23. export default class index extends Component {
    24. render() {
    25. return (
    26. <div>
    27. <ul className="newsList">
    28. <li>我是新闻组件1</li>
    29. <li>我是新闻组件2</li>
    30. <li>我是新闻组件3</li>
    31. <li>我是新闻组件4</li>
    32. <li>我是新闻组件5</li>
    33. <li>我是新闻组件6</li>
    34. </ul>
    35. </div>
    36. )
    37. }
    38. }

    根组件app.jsx

    1. // import axios from 'axios'
    2. import React, {
    3. Component
    4. } from 'react'
    5. import {Link,Route,Switch,Redirect} from 'react-router-dom'
    6. import Home from './components/Home'
    7. import About from './components/About'
    8. import Login from './components/Login'
    9. // import AddName from './components/Text'
    10. import "./index.css"
    11. class App extends Component {
    12. render() {
    13. return (
    14. <div>
    15. <div className="box">
    16. <div className="box_list">
    17. <div>
    18. <Link to="/home"> 主页</Link>
    19. </div>
    20. <div>
    21. <Link to="/about">关于</Link>
    22. </div>
    23. </div>
    24. <div className="box_content">
    25. <Switch>
    26. <Route path="/home" component={Home} />
    27. <Route path="/about" component={About}/>
    28. <Redirect to="/home"></Redirect>
    29. </Switch>
    30. </div>
    31. </div>
    32. </div>
    33. )
    34. }
    35. }
    36. export default App