1.首先需要定义两个子路由组件
2.在父组件中引入两个定义好的组件
3.通过link标签实现导航
4在switch定义路由组件,匹配对应路由组件
5.这里的匹配路劲需要带上父组件的路由路径
6.重定向路由组件,使得初始页面时路由组件可以默认渲染
父组件
import React, { Component } from 'react'
import {Link,Route,Switch,Redirect} from 'react-router-dom'
import Message from './Message'
import News from './News'
import "./index.css"
export default class Index extends Component {
render() {
return (
<div>
<h1>我是home组件</h1>
<ul className="navList">
<li>
<Link to="/home/message">消息组件</Link>
</li>
<li>
<Link to="/home/news">新闻组件</Link>
</li>
</ul>
<div>
<Switch>
<Route path="/home/message" component={Message}></Route>
<Route path="/home/news" component={News}></Route>
<Redirect to="/home/news"></Redirect>
</Switch>
</div>
</div>
)
}
}
路由子组件
//Message.jsx
import React, { Component } from 'react'
import "./index.css"
export default class index extends Component {
render() {
return (
<div>
<ul className="messageList">
<li>我是消息组件1</li>
<li>我是消息组件2</li>
<li>我是消息组件3</li>
<li>我是消息组件4</li>
<li>我是消息组件5</li>
<li>我是消息组件6</li>
</ul>
</div>
)
}
}
//News.jsx
import React, { Component } from 'react'
import "./index.css"
export default class index extends Component {
render() {
return (
<div>
<ul className="newsList">
<li>我是新闻组件1</li>
<li>我是新闻组件2</li>
<li>我是新闻组件3</li>
<li>我是新闻组件4</li>
<li>我是新闻组件5</li>
<li>我是新闻组件6</li>
</ul>
</div>
)
}
}
根组件app.jsx
// import axios from 'axios'
import React, {
Component
} from 'react'
import {Link,Route,Switch,Redirect} from 'react-router-dom'
import Home from './components/Home'
import About from './components/About'
import Login from './components/Login'
// import AddName from './components/Text'
import "./index.css"
class App extends Component {
render() {
return (
<div>
<div className="box">
<div className="box_list">
<div>
<Link to="/home"> 主页</Link>
</div>
<div>
<Link to="/about">关于</Link>
</div>
</div>
<div className="box_content">
<Switch>
<Route path="/home" component={Home} />
<Route path="/about" component={About}/>
<Redirect to="/home"></Redirect>
</Switch>
</div>
</div>
</div>
)
}
}
export default App