React 路由
介绍
路由: 在单页面应用中,路由就是让用户从一个页面跳转到另一个页面
路由的基本使用
-
安装:npm i react-router-dom / yarn add react-router-dom
-
导入路由的三大核心组件: Router/ Route/ Link
-
使用 Router组件包裹整个应用
-
使用 Link组件作为导航菜单(路由的路口)
-
使用 Route 组件配置路由规则和要展示的组件
// 1.引入三大核心组件
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
// 页面一
class First extends React.Component{
render() {
return (
<div>
<h1>页面一内容</h1>
</div>
)
}
}
// 页面二
class Two extends React.Component{
render() {
return (
<div>
<h1>页面二内容</h1>
</div>
)
}
}
// 2.使用 Router 组件包裹整个应用
class App extends React.Component{
render() {
return (
<Router>
<div>
<Link to="/first">页面一</Link>
<Link to="/two">页面二</Link>
<Route path="/first" component={First}></Route>
<Route path="/two" component={Two}></Route>
</div>
</Router>
)
}
}
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<App />
)
常用的路由组件
-
BrowserRouter : 包裹整个应用,让在这里面可以使用路由组件。原理是 H5 的history API 实现。
-
HashRouter : 跟 vue 中 的hash 路由差不多。URL 地址中都有 #。
-
Link : 用于指定跳转的链接
-
Route : 指定路由展示组件相关信息
-
path 属性:路由规则
-
component 属性:展示的组件
-
编程式导航
编程式导航: 通过 JS 代码来实现页面跳转
通过 this.props.history 来获取到浏览器历史记录。然后再通过 push 跳转到某个页面。---- this.props.history.push('/xxx')
匹配模式
模糊匹配
react 路由匹配使用到的就是 模糊匹配规则
模糊匹配规则:只要 pathname 以 path 开头,就会被匹配成功。--- (匹配 '/home' 的时候,也能匹配到 '/')
精确匹配
前提问题:要解决默认路由什么情况下都会进行展示。
解决方式: 在 Route 组件中添加 exact 属性,就会变成 精确匹配模式
精确匹配规则 :只有当 path 和 pathname 完全匹配的时候才会展示该路由。