1.下载react-router-dom 5的版本
npm i react-router-dom@5
2.在index.js中从react-router-dom中引入 BrowserRouter和HashRouter
BrowserRouter 使用历史模式history来管理路由
HashRouter 使用哈希模式hash来管理路由
// 将引入的BrowserRouter模块取一个别名叫Router
import { BrowserRouter as Router } from 'react-router-dom'
3.将App根组件用Router组件包裹起来
React-router-dom路由系统要求一个路由系统只能有一个Router
root.render(
<React.StrictMode>
{/* 将App根组件用<Router></Router>组件包裹起来 */}
<Router>
<App />
</Router>
</React.StrictMode>
)
4.分别创建Home和Course组件
import { Component } from "react";
export default class Home extends Component {
render() {
return (
<div>Home</div>
)
}
}
import { Component } from "react";
export default class Course extends Component {
render() {
return (
<div>Course</div>
)
}
}
5.在App组件中从react-router-dom中引入Route模块
// 引入Route模块
import { Route } from 'react-router-dom'
6.通过Route模块的path属性和component属性设置路径和组件的对应关系
import Course from './Course.js'
import Home from './Home.js'
class App extends PureComponent {
render() {
return (
<div id="app">
<Route path="/home" component={Home}></Route>
<Route path="/course" component={Course}></Route>
</div>
)
}
}
7.从react-router-dom中引入Link模块,添加路由跳转
import { PureComponent } from "react";标签:react,dom,---,router,import,Home,路由 From: https://www.cnblogs.com/toufuwqm/p/16916985.html
// 引入Route模块
import { Link, Route } from 'react-router-dom'
import Course from './Course.js'
import Home from './Home.js'
class App extends PureComponent {
render() {
return (
<div id="app">
{/*
实现路由跳转
Link模块的to属性可以是一个字符串,也可以是一个对象
*/}
{/* <Link to="/home">首页</Link > */}
<Link to={{ pathname: '/home' }}>首页</Link >
<Link to="/course">课程</Link >
<Route path="/home" component={Home}></Route>
<Route path="/course" component={Course}></Route>
</div>
)
}
}
export default App