Router:路由
目前有三種方法來控制路由
1. window.location.hash = '路由地址' //推薦使用
2. window.location.pathname = '路由地址' //不推薦使用,會刷新頁面
3. window.history.pushState(null,'','路由地址') //不是很推薦,需要后端將所有路徑都指向首頁
要想使用React Router,先引入react-router-dom依賴,然后在js里
import { BrowserRouter as Router, Route, Link } from "r··eact-router-dom";
現(xiàn)在就可以使用了
import React from "react";
import ReactDOM from "react-dom";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import "./styles.css";
function Box1() {
return <div className="box">登錄</div>;
}
function Box2() {
return <div className="box">注冊</div>;
}
function Box3() {
return <div className="box">歡迎</div>;
}
function App() {
return <div className="box">App</div>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Router>
<div>
<div>
<Link to="/" component={App}>
首頁
</Link>
<br/>
<Link to="/login" component={Box1}>
登錄
</Link>
<br />
<Link to="/signup" component={Box2}>
注冊
</Link>
<br />
<Link to="/welcome" component={Box3}>
歡迎
</Link>
</div>
<Route path="/" exact component={App} />
<Route path="/login/" component={Box1} />
<Route path="/signup/" component={Box2} />
<Route path="/welcome" component={Box3} />
</div>
</Router>,
rootElement
);