React18 +ts 路由写法
命令:npm i react-router-dom
版本声明:
写法一:
src>router>index.tsx
import App from "../App";
import React, { lazy } from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
const Home = lazy(() => import("../views/Home"));
// 抽取懒加载组件
const withReactSuspense = (comp: JSX.Element) => (
// lazy路由懒加载 需要搭配 Suspense 组件进行优化
<React.Suspense fallback={<div>Loading...</div>}>{comp}</React.Suspense>
);
function baseRouter() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
{/* Navigate 重定向 */}
<Route path="/" element={<Navigate to="/home" />}></Route>
<Route
path="/home"
element={
withReactSuspense(<Home />)
}
></Route>
</Route>
</Routes>
</BrowserRouter>
);
}
export default baseRouter;
main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import Router from "./router";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<Router />
</React.StrictMode>
);
App.tsx
import { Outlet } from "react-router-dom";
function App() {
return (
<div className="App">
{/* Outlet 占位符组件,类似于vue的router-view */}
<Outlet />
</div>
);
}
export default App;
第二种写法:
原文地址:https://blog.csdn.net/CSSAJBQ_/article/details/130131774
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!