React 基础教程:手把手创建计数器应用
·
React 基础教程:手把手创建计数器应用
本教程将带您逐步构建一个简单的 React 计数器应用,包含增加、减少和重置功能。
步骤 1:创建 React 项目
在终端执行以下命令:
npx create-react-app counter-app
cd counter-app
npm start
项目启动后,浏览器会自动打开 http://localhost:3000 显示默认页面。
步骤 2:创建计数器组件
- 在
src目录新建Counter.js文件 - 编写组件代码:
import React, { useState } from 'react';
function Counter() {
// 使用 useState 管理计数状态
const [count, setCount] = useState(0);
// 增加计数
const increment = () => setCount(count + 1);
// 减少计数
const decrement = () => setCount(count - 1);
// 重置计数
const reset = () => setCount(0);
return (
<div className="counter">
<h1>计数器: {count}</h1>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
<button onClick={reset}>重置</button>
</div>
);
}
export default Counter;
步骤 3:集成到主应用
修改 src/App.js 文件:
import React from 'react';
import Counter from './Counter';
import './App.css';
function App() {
return (
<div className="App">
<Counter />
</div>
);
}
export default App;
步骤 4:添加样式
在 src/App.css 中添加基础样式:
.counter {
text-align: center;
margin: 50px auto;
max-width: 300px;
}
button {
margin: 10px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #61dafb;
border: none;
border-radius: 5px;
}
button:hover {
background-color: #21a1f1;
}
步骤 5:运行应用
终端执行命令:
npm start
最终效果
- 初始计数为 $0$
- 点击
+1按钮:计数增加 $1$,即 $count \rightarrow count+1$ - 点击
-1按钮:计数减少 $1$,即 $count \rightarrow count-1$ - 点击
重置按钮:计数归零,即 $count \rightarrow 0$

关键概念解析
-
useState钩子- 用于管理组件状态
- 语法:
const [state, setState] = useState(initialValue) - 本例中:
count存储当前值,setCount用于更新值
-
事件处理
- 通过
onClick绑定按钮点击事件 - 触发时调用对应的函数(如
increment)
- 通过
-
状态更新
- 调用
setCount(newValue)会触发组件重新渲染 - 更新后的值会实时显示在界面上
- 调用
提示:尝试扩展功能(如添加「+5」按钮)来巩固学习!
更多推荐


所有评论(0)