React-路由


React路由

前端路由功能:让用户从一个视图导航到另一个视图 前端路由是一套映射规则,在React中,是URL和组件对应关系 使用React路由简单来说,就是配置路径和组件(配对)  

路由的基本使用

 
import React from 'react';
import ReactDOM from 'react-dom/client';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'

const First = () => (

页面一的内容

) //使用Router组件包裹整个应用 const App1 = () => (

React路由基础

{/* 指定路由入口 */} to属性:浏览器地址栏中的pathname(location.pathname) 页面一 {/* 指定路由出口 */} {/* route组件写在哪,渲染出来的组件就展示在哪 */} } />
) const container = document.getElementById('root') const root = ReactDOM.createRoot(container) root.render();

路由的执行过程

1.点击Link组件(a标签),修改了浏览器地址栏中的url 2.React路由监听到地址栏url变化 3.React路由内部遍历所有Route组件,使用路由规则(path)与pathname进行匹配 4.当路由规则(path)能够匹配地址栏中的pathname时,就展示该Route组件的内容
const First = () => (

页面一的内容

) const Home = () =>

home内容

//使用Router组件包裹整个应用 const App1 = () => (

React路由基础

{/* 指定路由入口 */} {/* to属性:浏览器地址栏中的pathname(location.pathname) */} 页面一
home页面 {/* 指定路由出口 */} {/* route组件写在哪,渲染出来的组件就展示在哪 */} } /> } />
)

编程式导航

通过js实现页面跳转
//编程式导航
class Login extends React.Component {
  handelLogin = () => {
    this.props.history.push('/home')
  }
  render() {
    return (
      

登录页面:

) } } const Home = (props) => { const handleBack = () => { props.history.go(-1) } return ( < div >

我是后台首页

) } const App = () => (

编程式导航:

去登录首页 } /> } />
) const root = ReactDOM.createRoot(document.getElementById('root')) root.render()

默认路由

 
const Home = () => (
  

进入页面就会匹配的路由

) const App = () => (

默认路由

} />
) const root = ReactDOM.createRoot(document.getElementById('root')) root.render()

匹配模式

模糊匹配模式 模糊匹配模式:只要pathname以path开头就会匹配成功   精确匹配模式
const App = () => (
  
    

默认路由

精确 } /> {/* 精确匹配,只需要加入exact属性 */} } />
)