React实现小功能
React 实现小功能的常见方法
创建计数器组件
使用 useState 钩子管理状态,实现点击按钮增减数值的功能:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count - 1)}>-</button>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
}
表单输入实时显示
通过 onChange 事件同步输入框内容到状态:
function InputDisplay() {
const [text, setText] = useState('');
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<p>输入内容: {text}</p>
</div>
);
}
待办事项列表
结合数组状态管理和条件渲染实现添加/删除任务:
function TodoList() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const addTodo = () => {
if (input.trim()) {
setTodos([...todos, input]);
setInput('');
}
};
return (
<div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={addTodo}>添加</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() =>
setTodos(todos.filter((_, i) => i !== index))
}>删除</button>
</li>
))}
</ul>
</div>
);
}
自定义 Hook 封装
复用逻辑的典型示例(如窗口尺寸监听):
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
// 使用示例
function DisplayWidth() {
const width = useWindowWidth();
return <div>窗口宽度: {width}px</div>;
}
注意事项
- 事件处理函数使用箭头函数避免
this绑定问题 - 列表渲染需添加唯一
key属性 - 副作用操作(如数据请求)应在
useEffect中完成 - 组件拆分保持单一职责原则







