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";
现在就可以使用了
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
);
网友评论