react如何开发项目
React 项目开发流程
环境准备 安装 Node.js(建议 LTS 版本),使用 npm 或 yarn 作为包管理工具。全局安装 create-react-app 脚手架工具:
npm install -g create-react-app
项目初始化 通过脚手架创建新项目:
npx create-react-app my-app
cd my-app
npm start
项目结构说明
src/:核心开发目录App.js:根组件index.js:入口文件
public/:静态资源package.json:依赖配置
核心开发步骤
组件开发 创建函数组件或类组件:
// 函数组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// 类组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
状态管理 使用 useState Hook(函数组件):
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
生命周期管理 使用 useEffect Hook:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // 仅在count变化时更新
路由配置
安装 react-router-dom:
npm install react-router-dom
基本路由示例:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
);
}
状态管理进阶
Redux 集成示例:
- 安装必要依赖:
npm install redux react-redux - 创建 store:
import { createStore } from 'redux';
function counterReducer(state = 0, action) { switch(action.type) { case 'INCREMENT': return state + 1; default: return state; } }
const store = createStore(counterReducer);
### 样式方案
CSS Modules
创建 `Component.module.css` 文件:
```css
.button {
background: blue;
}
组件中使用:
import styles from './Component.module.css';
<button className={styles.button}>Submit</button>
Styled-components 安装:
npm install styled-components
使用示例:
import styled from 'styled-components';
const Button = styled.button`
background: ${props => props.primary ? 'blue' : 'white'};
`;
<Button primary>Click</Button>
构建与部署
生产环境构建:
npm run build
部署到任意静态服务器,或使用 serve 测试:

npm install -g serve
serve -s build






