1.Vite官网开始 | Vite 官方中文文档 (vitejs.dev)
2.
3.
生成框架如下:
4.基本框架的搭建实现一个可以路由跳转的功能
routerCOnfig.ts
import { lazy } from "react";
// 引入路由类型
import { RouterItem, RouterList } from "../utills/type";
// 定义二级路由,包含具体的页面路径和元素,以及标题
export const homeRouters: RouterItem[] = [
{
path: '/home/index',
element: lazy(() => import('../Views/Index/index')),
title: "首页"
},
{
path: '/home/project',
element: lazy(() => import('../Views/Project/index')),
title: "项目"
},
]
// 定义一级路由配置,使用history模式
// 包含根路径重定向、home路由、Login路由和默认错误页面
const routerList: RouterList = {
mode: 'history',
routes: [
{
path: '/',
to: '/home/index',
},
{
path: '/home',
element: lazy(() => import('../Views/Home/index')),
children: homeRouters,// 嵌套子路由
},
{
path: '/login',
element: lazy(() => import('../Views/Login/index')),
},
{
path: '*',
element: lazy(() => import('../Views/Error/index')),
}
]
}
export default routerList// 导出路由配置供其他模块使用
utills下的定义路由类型
import { JSXElement } from "react";
//定义了路由项的类型,包含了路径、跳转地址、标题、元素、子路由和推送功能
export type RouterItem={
path?: string, // 路径
to?: string, // 跳转地址
title?: string, // 标题
element?: JSXElement, // React元素
children?: RouteItem[], // 子路由项数组
push?:any // 推送功能,具体类型根据实际情况定义
}
//定义了路由列表的类型,包含了模式和路由项数组
export type RouterList={
mode:string, // 模式名称
routes:RouteItem[] // 路由项数组
}
routerView.tsx
import {Suspense} from 'react' // 导入React库和Suspense组件
import { BrowserRouter,HashRouter,Route,Routes,Navigate } from 'react-router-dom' // 导入React Router相关组件
import routerList from './routerConfig' // 导入路由配置
import { RouterItem } from '../utills/type' // 导入路由项类型定义
// 该组件根据routerList配置渲染对应的路由
function RouterView() {
// 解构获取路由模式和路由数组
const {mode,routes}=routerList;
// 递归渲染路由数组中的每个路由项
const rendeRoutes=(arr:RouterItem[])=>{
return arr && arr.map((item,index)=>{
return <Route key={index} path={item.path} element={item.to?<Navigate to={item.to}></Navigate>:<item.element></item.element>}>
{
// 如果有子路由,递归调用rendeRoutes
item.children && rendeRoutes(item.children)
}
</Route>
})
}
return (
// 使用Suspense处理路由组件异步加载状态 白屏优化
<Suspense fallback={<div>加载中.......</div>}>
{
// 根据模式选择渲染BrowserRouter或HashRouter
mode==="history"?<BrowserRouter>
<Routes>
{
rendeRoutes(routes) // 根据路由配置渲染路由
}
</Routes>
</BrowserRouter>:<HashRouter>
<Routes>
{
rendeRoutes(routes) // 根据路由配置渲染路由
}
</Routes>
</HashRouter>
}
</Suspense>
)
}
export default RouterView // 导出路由视图组件
App.tsx导入路由
页面写路由出口以供跳转
使用的组件链接 Ant Design of React - Ant Design
1.下包: