如何直接使用react框架
使用 React 框架的直接方法
安装 Node.js 和 npm
React 需要 Node.js 环境,确保安装最新版本的 Node.js(包含 npm)。可以从 Node.js 官网 下载并安装。
创建 React 应用
使用官方工具 create-react-app 快速搭建项目。运行以下命令生成新项目:
npx create-react-app my-app
my-app 是项目名称,可根据需求修改。
启动开发服务器
进入项目目录并启动开发服务器:
cd my-app
npm start
默认会在浏览器中打开 http://localhost:3000 并显示 React 欢迎页面。
编写 React 组件
创建组件文件
在 src 目录下新建文件(如 MyComponent.js),编写函数式组件:
import React from 'react';
function MyComponent() {
return <h1>Hello, React!</h1>;
}
export default MyComponent;
在入口文件中使用组件
修改 src/App.js,引入并渲染自定义组件:
import MyComponent from './MyComponent';
function App() {
return (
<div className="App">
<MyComponent />
</div>
);
}
管理状态和交互
使用 Hooks 管理状态
在函数组件中使用 useState 添加状态:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
构建与部署
生成生产环境代码
运行构建命令生成优化后的代码:
npm run build
构建结果会保存在 build 目录中,可直接部署到静态服务器。
配置自定义服务器
如需后端支持,可结合 Express 等 Node.js 框架。示例 server.js:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
进阶功能
路由配置
安装 react-router-dom 实现页面导航:
npm install react-router-dom
示例路由配置:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="/about">About</Link>
<Route path="/about" component={About} />
</Router>
);
}
状态管理
使用 Redux 或 Context API 管理全局状态。安装 Redux:

npm install redux react-redux






