目录
十七、react-router的使用
1、URL的hash
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue-router</title>
</head>
<body>
<a href="#/home">home</a>
<a href="#/about">about</a>
<div class="router-view"></div>
<script>
const routerView = document.querySelector(".router-view")
addEventListener("hashchange", () => {
switch (location.hash) {
case "#/home":
routerView.innerHTML = "home"
break;
case "#/about":
routerView.innerHTML = "about"
break;
default:
routerView.innerHTML = "default"
}
})
</script>
</body>
</html>
2、HTML5的History
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue-router</title>
</head>
<body>
<a href="/home" onclick="routerHandler(event,this)">home</a>
<a href="/about" onclick="routerHandler(event,this)">about</a>
<div class="router-view"></div>
<script>
const routerView = document.querySelector(".router-view")
const changeContent = (pathname) => {
switch (pathname) {
case "/home":
routerView.innerHTML = "home"
break;
case "/about":
routerView.innerHTML = "about"
break;
default:
routerView.innerHTML = "default"
}
}
/**
* 1、history接口是HTML5新增的,它有六种模式改变URL而不刷新页面
* - replaceState:替换原来的路径
* - pushState:使用新的路径
* - popState:路径的回退
* - go:向前或向后改变路径
* - forward:向前改变路径
* - back:向后改变路径
*/
const routerHandler = (ev, el) => {
ev.preventDefault()
const href = el.getAttribute("href");
history.pushState({}, "", href)
changeContent(location.pathname)
}
addEventListener("popstate", changeContent)
</script>
</body>
</html>
3、router的基本使用
- src/layout/App.js
import React, {PureComponent} from "react";
// npm i react-router-dom
import {HashRouter, Link, Routes, Route} from "react-router-dom"
import routes from "@/routers"
/**
* 1、BrowserRouter或HashRouter
* - Router中包含了对路径改变的监听,并且会将相应的路径传递给子组件
* - BrowserRouter使用history模式
* - HashRouter使用hash模式
* 2、Link和NavLink
* - 通常路径的跳转是使用Link组件,最终会被渲染成a元素
* - NavLink是在Link基础之上增加了一些样式属性(后续学习)
* - to属性:Link中最重要的属性,用于设置跳转到的路径
* 3、Route(V5)
* - Route用于路径的匹配
* - path属性:用于设置匹配到的路径
* - component属性:设置匹配到路径后,渲染的组件
* - exact:精准匹配,只有精准匹配到完全一致的路径,才会渲染对应的组件
*/
export default class App extends PureComponent {
render() {
return (<HashRouter>
<Link to="/">首页</Link>
<Link to="/about">关于</Link>
<Link to="/profile">我的</Link>
<Routes>
{
routes.map(item => {
return (<Route key={item.name}
path={item.path}
element={<item.component/>}/>)
})
}
</Routes>
</HashRouter>)
}
}
- src/routers/index.js
import Home from "@/views/Home"
import About from "@/views/About"
import Profile from "@/views/Profile"
export default [{
name: "Home",
path: "/",
component: Home
}, {
name: "About",
path: "/about",
component: About
}, {
name: "Profile",
path: "/profile",
component: Profile
}]
4、
标签:about,routerView,路径,高级,innerHTML,react,第七章,router
From: https://www.cnblogs.com/linding/p/17054461.html