在 React 中动态地添加和删除数组中的值,通常是通过更新组件的状态 (state
) 来实现的。React 的状态更新是异步的,因此需要使用函数式的更新方法来确保状态的正确性。下面是一个详细的示例,展示如何在 React 中添加和删除数组中的元素。
我们将创建一个简单的待办事项列表,用户可以添加新的待办项,也可以删除现有的待办项。
jsximport React, { useState } from 'react';
function TodoList() {
// 初始化状态为一个空数组
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
// 处理输入变化
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
// 添加新的待办项
const addTodo = () => {
if (inputValue.trim() === '') return; // 避免添加空项
setTodos([...todos, inputValue]); // 使用展开运算符添加新项
setInputValue(''); // 清空输入框
};
// 删除指定索引的待办项
const deleteTodo = (index) => {
const newTodos = todos.filter((_, i) => i !== index); // 过滤掉指定索引的项
setTodos(newTodos);
};
return (
<div>
<h2>待办事项列表</h2>
<div>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="输入待办事项"
/>
<button onClick={addTodo}>添加</button>
</div>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => deleteTodo(index)}>删除</button>
</li>
))}
</ul>
</div>
);
}
export default TodoList;
todos
:存储待办事项的数组。inputValue
:存储输入框中的当前值。addTodo
函数会被调用。...todos
) 创建一个新的数组,并将新的待办项添加到末尾。todos
状态为新的数组,并清空输入框。deleteTodo
函数,并传入该项的索引。deleteTodo
函数使用 filter
方法创建一个新的数组,排除掉指定索引的项。todos
状态为新的数组,从而在 UI 中移除该项。虽然函数组件和 Hooks 是现代 React 开发的推荐方式,但你也可以使用类组件来实现相同的功能。下面是一个使用类组件的示例:
jsximport React, { Component } from 'react';
class TodoListClass extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
inputValue: '',
};
}
handleInputChange = (e) => {
this.setState({ inputValue: e.target.value });
};
addTodo = () => {
const { inputValue, todos } = this.state;
if (inputValue.trim() === '') return;
this.setState({
todos: [...todos, inputValue],
inputValue: '',
});
};
deleteTodo = (index) => {
const newTodos = this.state.todos.filter((_, i) => i !== index);
this.setState({ todos: newTodos });
};
render() {
const { todos, inputValue } = this.state;
return (
<div>
<h2>待办事项列表</h2>
<div>
<input
type="text"
value={inputValue}
onChange={this.handleInputChange}
placeholder="输入待办事项"
/>
<button onClick={this.addTodo}>添加</button>
</div>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => this.deleteTodo(index)}>删除</button>
</li>
))}
</ul>
</div>
);
}
}
export default TodoListClass;
key
):
key
属性来识别每个元素。在上面的示例中,我们使用了数组的索引作为 key
。然而,当列表项可能会重新排序或动态变化时,使用索引作为 key
可能会导致性能问题或错误。更好的做法是为每个待办项分配一个唯一的 ID,例如使用 UUID 或自增的 ID。React.memo
、useCallback
等优化手段,或者使用更高效的数据结构。你可以根据需要扩展此示例,例如:
localStorage
或后端服务器,以便刷新页面后数据依然存在。没有搜到相关的文章