安装路由插件—默认是6版本 npm i react-router-dom -s
这里查看
- 组件介绍
- 所有的需要使用路由组件都要包裹在
BrowserRouter 或者HashRouter 标签里面
Browser和HashRouter的主要区别: path表现形式不一样 BrowserRouter的路径中没有#,例如:localhost:3000/demo/test HashRouter的路径包含#,例如:localhost:3000/#/demo/test 刷新后对路由state参数的影响 BrowserRouter没有任何影响,因为state保存在history对象中。 HashRouter刷新后会导致路由state参数的丢失!!!
Link 跳转路由链接; NavLink 跳转路由链接,会为选中路由添加一个active 类名- 路由标签
Route ,写在Routes 标签内部,用于显示路由链接对应的组件 - 路由的重定向功能用
Navigate 实现 - 主要代码
index.js
用Router(BrowserRouter)标签包裹整个App组件
import React from "react";
import ReactDOM from 'react-dom/client'
import { BrowserRouter as Router} from 'react-router-dom'
import App from "./App";
const root = ReactDOM.createRoot(document.querySelector('#root'))
root.render(
<Router>
<App></App>
</Router>
)
App.js
import React from 'react'
import { Routes, NavLink, Route, Navigate } from 'react-router-dom'
import Home from './pages/Home'
import About from './pages/About'
export default function App() {
return (
<div>
<div className="row">
<div className="col-xs-offset-2 col-xs-8">
<div className="page-header"><h2>React Router Demo</h2></div>
</div>
</div>
<div className="row">
<div className="col-xs-2 col-xs-offset-2">
<div className="list-group">
<NavLink className="list-group-item" to="/about">About</NavLink>
<NavLink className="list-group-item" to="/home">Home</NavLink>
</div>
</div>
<div className="col-xs-6">
<div className="panel">
<div className="panel-body">
{}
<Routes>
<Route path='/about' element={<About/>}></Route>
{}
<Route path='/home/*' element={<Home/>}></Route>
{}
<Route path="*" element={<Navigate to={"/about"} replace />}></Route>
</Routes>
</div>
</div>
</div>
</div>
</div>
)
}
Home/jsx
import React from 'react'
import { Routes, Route, Navigate, NavLink } from 'react-router-dom'
import Message from './Message'
import News from './News'
export default function Home () {
return (
<div>
<h2>Home组件内容</h2>
<div>
<ul className="nav nav-tabs">
<li>
{}
{}
{}
<NavLink className="list-group-item" to='news'>News</NavLink>
</li>
<li>
<NavLink className="list-group-item" to='/home/message'>Message</NavLink>
</li>
</ul>
{}
<Routes>
<Route path='news' element={<News></News>}></Route>
<Route path='message' element={<Message></Message>}></Route>
<Route path='*' element={<Navigate to={'news'} replace></Navigate>}></Route>
</Routes>
</div>
</div>
)
}
About.jsx
import React from 'react'
export default function About() {
return (
<div>我是About组件</div>
)
}
News.jsx
import React, { Component } from 'react'
export default class News extends Component {
render() {
return (
<ul>
<li>news001</li>
<li>news002</li>
<li>news003</li>
</ul>
)
}
}
Message.jsx
import React, { Component } from 'react'
export default class Message extends Component {
render() {
return (
<div>
<ul>
<li>
<a href="/message1">message001</a>
</li>
<li>
<a href="/message2">message002</a>
</li>
<li>
<a href="/message/3">message003</a>
</li>
</ul>
</div>
)
}
}
代码使用了Bootstrap样式,需要public/index.html文件中引入
|