React Router

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
);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容