react中写一个简单的todolist增删改
时间: 2023-09-28 19:03:51 浏览: 46
好的,下面是一个简单的React TodoList组件,包含添加、删除和编辑功能:
```jsx
import React, { useState } from 'react';
const TodoList = () => {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
const [editIndex, setEditIndex] = useState(-1);
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const handleAddClick = () => {
if (inputValue.trim() === '') return;
if (editIndex === -1) {
setTodos([...todos, inputValue]);
} else {
const newTodos = [...todos];
newTodos[editIndex] = inputValue;
setTodos(newTodos);
setEditIndex(-1);
}
setInputValue('');
};
const handleDeleteClick = (index) => {
const newTodos = [...todos];
newTodos.splice(index, 1);
setTodos(newTodos);
};
const handleEditClick = (index) => {
setEditIndex(index);
setInputValue(todos[index]);
};
return (
<div>
<h1>Todo List</h1>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => handleDeleteClick(index)}>Delete</button>
<button onClick={() => handleEditClick(index)}>Edit</button>
</li>
))}
</ul>
<div>
<input type="text" value={inputValue} onChange={handleInputChange} />
<button onClick={handleAddClick}>{editIndex === -1 ? 'Add' : 'Save'}</button>
</div>
</div>
);
};
export default TodoList;
```
上述代码中,我们使用useState hooks来管理todos、inputValue和editIndex三个状态。其中todos存储所有的todo项,inputValue表示输入框的值,editIndex表示当前正在编辑的todo项的索引。
handleInputChange函数用来处理输入框值的变化,handleAddClick函数用来添加或修改todo项,handleDeleteClick函数用来删除todo项,handleEditClick函数用来启动编辑模式。
在render函数中,我们使用map函数遍历todos数组,渲染每个todo项。对于每个todo项,我们渲染一个删除按钮和一个编辑按钮,点击这两个按钮分别会调用handleDeleteClick和handleEditClick函数。在最后,我们渲染一个输入框和一个添加/保存按钮,点击添加/保存按钮会调用handleAddClick函数。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)