【无标题】

一:创建项目

超全面详细一条龙教程!从零搭建React项目全家桶(上篇) - 知乎

1.创建一个文件夹,shift+鼠标右键选择在此处打开powershell

2.为了加速npm下载速度,先把npm设置为淘宝镜像地址。

npm config set registry http://registry.npm.taobao.org/

3.执行下面的npm安装react,那么基础的项目就搭建好了

npx create-react-app react-app

4.使用下列npm运行项目

npm start

二:精简项目

删除例如App.css、App.test.js、index.css、logo.svg、reportWebvitals.js、setupTests.js等文件,

保留核心index.js、App.js;优化成下图

三.创建文件并安装路由

1.基本文件格式

2.安装路由 npm install react-router-dom

  1. router文件夹下index.js的模板
javascript 复制代码
// 引入组件
import Login from "../views/login";
// 注册路由数组
const routes = [
  {
    // 首页默认是/
    path: "/",
    element: <Login></Login>,
  }
];
// 导出
export default routes;
  1. views文件夹下面的页面的基本模板结构
javascript 复制代码
import React from "react";
export default function login() {
  return <div>这是子页面</div>;
}

5.配置 App.js 使用路由 : 在 App.js 中使用 useRoutes 来注册路由:

javascript 复制代码
import { useRoutes } from 'react-router-dom';
import routes from './router';
 
function App() {
  return (
    <div>
      {/* 注册路由 */}
      {useRoutes(routes)}
    </div>
  );
}
 
export default App;

6.配置 index.js 引入 HashRouter : 在 index.js 中,使用 HashRouter 包裹 App 组件,配置路由:

javascript 复制代码
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { HashRouter } from 'react-router-dom'; // 导入 HashRouter
 
const root = ReactDOM.createRoot(document.getElementById('root'));
 
root.render(
  <HashRouter>
    <App />
  </HashRouter>
);

7.index.html替换为

javascript 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1"
/>
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using createreact-app" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
相关推荐
码农小旋风3 天前
Claude Code 最佳实践指南
arcgis
兔年鸿运Q小Q13 天前
cesium1.140以上版本加载地形
arcgis·cesium
杨超越luckly14 天前
Agent应用指南:巨幕之下 · 中国 IMAX 影院205城的空间布局
人工智能·arcgis·html·agent·数据可视化
GISerQ.15 天前
DWG格式文件导入到ArcGIS中
arcgis·shp·cad文件·dwg文件
En^_^Joy20 天前
Vue项目创建与入口配置全攻略
前端·vue.js·arcgis
图件制作GIS,储量计算20 天前
补充耕地项目类、非项目类资料清单
arcgis
不在逃避q20 天前
Trae/Vs Code/Cursor命令行无法跑npm命令
前端·arcgis·npm
GISerQ.22 天前
ArcGIS实现矢量拓扑检查与修复
arcgis·拓扑检查·拓扑修复
NutShell Wang22 天前
零依赖架构实战:451个HTML文件如何用63KB平均体积交付3584个交互模块
前端·人工智能·arcgis·npm·开源·html·vibe coding
开开心心就好22 天前
电脑内存优化工具一键释放内存超简单
java·开发语言·macos·arcgis·ocr·excel·音视频