react hooks todolist
时间: 2023-12-11 18:04:49 浏览: 84
React版本的todoList案例源码
以下是一个使用React Hooks实现的TodoList示例:
```jsx
import React, { useState } from 'react';
import List from './List/List';
export default function TodoList() {
const [inputValue, setInputValue] = useState(''); // 用于输入框的值
const [list, setList] = useState([]); // 用于存储todo列表
// 处理输入框值变化
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
// 处理添加todo
const handleAddTodo = () => {
if (inputValue.trim()) {
setList([...list, { id: Date.now(), content: inputValue }]);
setInputValue('');
}
};
// 处理删除todo
const handleDeleteTodo = (id) => {
setList(list.filter((item) => item.id !== id));
};
return (
<div>
<h1>TodoList</h1>
<div>
<input type="text" value={inputValue} onChange={handleInputChange} />
<button onClick={handleAddTodo}>添加</button>
</div>
<List list={list} onDeleteTodo={handleDeleteTodo} />
</div>
);
}
```
List组件:
```jsx
import React from 'react';
import Item from '../Item/Item';
export default function List(props) {
return (
<ul>
{props.list.map((item) => (
<Item key={item.id} item={item} onDeleteTodo={props.onDeleteTodo} />
))}
</ul>
);
}
```
Item组件:
```jsx
import React from 'react';
export default function Item(props) {
const handleDelete = () => {
props.onDeleteTodo && props.onDeleteTodo(props.item.id);
};
return (
<li>
{props.item.content}
<button onClick={handleDelete}>删除</button>
</li>
);
}
```
阅读全文