使用VS Code 生成 React 简单问候页面的完整步骤

Posted on 2026-03-26 13:28  打杂滴  阅读(1)  评论(0)    收藏  举报

第一步:环境准备‌

访问 Node.js 官网下载并安装最新 LTS 版本
安装 VS Code 编辑器
安装 VS Code 插件:ES7+ React/Redux snippets、ESLint、Prettier
第二步:项目初始化‌

打开 VS Code 终端(Terminal > New Terminal)
执行命令创建项目:
npx create-react-app greeting-app

创建项目日志如下:

PS F:\React> npx create-react-app greeting-app
Need to install the following packages:
create-react-app@5.1.0
Ok to proceed? (y) y

npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated glob@7.2.3: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for
old versions may be purchased (at exorbitant rates) by contacting i@izs.me
npm warn deprecated uid-number@0.0.6: This package is no longer supported.
npm warn deprecated fstream-ignore@1.0.5: This package is no longer supported.
npm warn deprecated rimraf@2.7.1: Rimraf versions prior to v4 are no longer supported
npm warn deprecated fstream@1.0.12: This package is no longer supported.
npm warn deprecated tar@2.2.2: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
create-react-app is deprecated.

You can find a list of up-to-date React frameworks on react.dev
For more info see:https://react.dev/link/cra

This error message will only be shown once per install.

Creating a new React app in F:\React\greeting-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...


added 1297 packages in 2m

268 packages are looking for funding
run `npm fund` for details

Initialized a git repository.

Installing template dependencies using npm...

added 17 packages, and changed 1 package in 17s

268 packages are looking for funding
run `npm fund` for details
Removing template package using npm...


removed 1 package, and audited 1314 packages in 10s

268 packages are looking for funding
run `npm fund` for details

26 vulnerabilities (9 low, 3 moderate, 14 high)

To address issues that do not require attention, run:
npm audit fix

To address all issues (including breaking changes), run:
npm audit fix --force

Run `npm audit` for details.
Git commit not created Error: Command failed: git commit -m "Initialize project using Create React App"
at genericNodeError (node:internal/errors:983:15)
at wrappedFn (node:internal/errors:537:14)
at checkExecSyncError (node:child_process:882:11)
at execSync (node:child_process:954:15)
at tryGitCommit (F:\React\greeting-app\node_modules\react-scripts\scripts\init.js:62:5)
at module.exports (F:\React\greeting-app\node_modules\react-scripts\scripts\init.js:350:25)
at [eval]:3:14
at runScriptInThisContext (node:internal/vm:209:10)
at node:internal/process/execution:449:12
at [eval]-wrapper:6:24 {
status: 128,
signal: null,
output: [ null, null, null ],
pid: 25988,
stdout: null,
stderr: null
}
Removing .git directory...

Success! Created greeting-app at F:\React\greeting-app
Inside that directory, you can run several commands:

npm start
Starts the development server.

npm run build
Bundles the app into static files for production.

npm test
Starts the test runner.

npm run eject
Removes this tool and copies build dependencies, configuration files
and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

cd greeting-app
npm start

Happy hacking!


PS F:\React>

image

 

使用 npx create-react-app greeting-app 命令创建项目后,会生成一个标准的 React 项目结构。以下是各个核心文件和目录的作用详解:

项目根目录结构:

 

greeting-app/
├── package.json
├── public/
├── src/
└── README.md

public 目录
该目录存放所有不需要经过构建过程处理的静态资源文件:

index.html‌:应用程序的主 HTML 模板文件,包含基础的 HTML 结构和 meta 标签。其中的 <div id="root"></div> 是 React 应用的挂载点。
favicon.ico‌:网站图标文件。
manifest.json‌:用于定义 PWA(渐进式 Web 应用)的配置文件。
robots.txt‌:搜索引擎爬虫配置文件。

 

src 目录
该目录是 React 应用的核心源代码目录:

App.js‌:主 React 组件文件,是应用程序的根组件。你可以在此编写应用的主要逻辑和 UI 结构。
App.css‌:App 组件的样式文件。
index.js‌:应用程序的入口文件,负责渲染根组件。该文件通过 ReactDOM.render() 方法将 App 组件挂载到 public/index.html 中的 <div id="root"></div> 元素上。
index.css‌:应用的全局样式文件。
App.test.js‌:App 组件的自动化测试文件。
setupTests.js‌:测试环境的配置文件。

package.json 文件
该文件包含项目的基本信息、依赖项和脚本命令:

name‌:项目名称。
version‌:项目版本号。
scripts‌:定义了开发、构建、测试等常用命令,如 npm start、npm run build 等。
dependencies‌:项目运行时依赖的包列表,如 React 和 React DOM 等。

核心文件作用总结
index.js‌:作为整个 React 应用的入口点,负责初始化并渲染根组件。
App.js‌:定义了应用的主要 UI 结构和交互逻辑。
App.css‌:用于为 App 组件提供样式。
public/index.html‌:定义了应用的 HTML 模板和挂载点。
通过以上结构,React 应用能够清晰地组织代码、管理样式和处理用户交互。


等待安装完成后进入项目目录:
cd greeting-app

 

第三步:安装必要依赖‌
项目已包含 React 核心依赖,可根据需要安装额外组件: package.json

image

 

第四步:开发问候页面组件‌
替换 src/App.js 文件内容实现问候功能:


import React, { useState } from 'react';
import './App.css';

function App() {
  const [name, setName] = useState('');
  const [greeting, setGreeting] = useState('');

  const handleGreet = () => {
    if (name.trim()) {
      setGreeting(`你好, ${name}! 欢迎来到React世界!`);
    } else {
      setGreeting('请输入您的姓名');
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleGreet();
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>React 问候页面</h1>
        <div className="greeting-container">
          <input
            type="text"
            placeholder="请输入您的姓名"
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyPress={handleKeyPress}
            className="name-input"
          />
          <button onClick={handleGreet} className="greet-button">
            问候
          </button>
          {greeting && (
            <div className="greeting-message">
              {greeting}
            </div>
          )}
        </div>
      </header>
    </div>
  );
}

export default App;

第五步:美化界面样式‌
修改 src/App.css 添加现代化样式:


.App {
  text-align: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-family: Arial, sans-serif;
}

.App-header {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  width: 80%;
  max-width: 500px;
}

.App-header h1 {
  color: #333;
  margin-bottom: 1.5rem;
  font-size: 2rem;
}

.greeting-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  align-items: center;
}

.name-input {
  padding: 0.8rem 1.2rem;
  font-size: 1rem;
  border: 2px solid #667eea;
  border-radius: 25px;
  outline: none;
  width: 100%;
  max-width: 300px;
  transition: all 0.3s ease;
}

.name-input:focus {
  border-color: #764ba2;
  box-shadow: 0 0 10px rgba(118, 75, 162, 0.3);
}

.greet-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 0.8rem 2rem;
  font-size: 1rem;
  border-radius: 25px;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.greet-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.greet-button:active {
  transform: translateY(0);
}

.greeting-message {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #f0f8ff;
  border-radius: 10px;
  border-left: 4px solid #667eea;
  color: #333;
  font-size: 1.1rem;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
  .App-header {
    width: 90%;
    padding: 1.5rem;
  }
 
  .App-header h1 {
    font-size: 1.5rem;
  }
}
 

第六步:启动开发服务器‌
在终端执行 npm start 命令启动应用,默认在 http://localhost:3000 访问

image

 

 

image

 

package.json:定义了React项目核心依赖(create-react-app默认配置)和运行脚本
src/App.js:实现了带状态管理的问候功能组件,支持键盘事件和点击交互
src/App.css:提供了现代化渐变背景、毛玻璃效果和动画过渡的响应式样式

 

 

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3