react 实现增加
使用 useState Hook 实现数据增加
在 React 中,可以通过 useState Hook 来管理状态,并通过事件处理函数实现数据的增加功能。
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>当前计数: {count}</p>
<button onClick={increment}>增加</button>
</div>
);
}
在数组中添加新元素
如果需要在一个数组中添加新元素,可以结合展开运算符和 useState 实现。

import React, { useState } from 'react';
function ItemList() {
const [items, setItems] = useState(['苹果', '香蕉']);
const addItem = () => {
const newItem = '橘子';
setItems([...items, newItem]);
};
return (
<div>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<button onClick={addItem}>添加水果</button>
</div>
);
}
表单提交实现数据增加
通过表单输入新数据并提交,可以动态增加内容。

import React, { useState } from 'react';
function AddTodo() {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
if (inputValue.trim()) {
setTodos([...todos, inputValue]);
setInputValue('');
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit">添加</button>
</form>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
);
}
使用 useReducer 管理复杂状态
对于更复杂的状态逻辑,可以使用 useReducer 替代 useState。
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>当前计数: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>增加</button>
</div>
);
}
动态增加组件
可以通过状态管理动态渲染新的组件实例。
import React, { useState } from 'react';
function DynamicComponents() {
const [components, setComponents] = useState([]);
const addComponent = () => {
setComponents([...components, <div key={components.length}>新增组件 {components.length + 1}</div>]);
};
return (
<div>
<button onClick={addComponent}>添加组件</button>
{components}
</div>
);
}






