React 实战 Todolist
import React, { useState } from 'react';
import 'antd/dist/antd.css';
import { Input, Button, List, Checkbox } from 'antd';
const App = () => {
const [tasks, setTasks] = useState([]);
const [inputValue, setInputValue] = useState('');
const handleChange = e => {
setInputValue(e.target.value);
};
const handleAdd = () => {
if (inputValue.trim() === '') return;
setTasks([...tasks, { id: Date.now(), name: inputValue, done: false }]);
setInputValue('');
};
const handleDelete = id => {
setTasks(tasks.filter(task => task.id !== id));
};
const handleCheck = id => {
setTasks(
tasks.map(task =>
task.id === id ? { ...task, done: !task.done } : task
)
);
};
const handleClear = () => {
setTasks(tasks.filter(task => !task.done));
};
return (
<div style={{ margin: '10px 20px' }}>
<Input
value={inputValue}
onChange={handleChange}
placeholder="请输入任务"
style={{ marginBottom: '10px', width: '300px' }}
/>
<Button type="primary" onClick={handleAdd}>
添加任务
</Button>
<Button onClick={handleClear} style={{ margin: '0 10px' }}>
清除已完成
</Button>
<List
bordered
dataSource={tasks}
renderItem={item => (
<List.Item
actions={[
<Checkbox
checked={item.done}
onChange={() => handleCheck(item.id)}
/>,
<Button onClick={() => handleDelete(item.id)} type="danger">
删除
</Button>,
]}
>
{item.name}
</List.Item>
)}
/>
</div>
);
};
export default App;
这段代码是对上一个代码块的完善,它包括了输入框的值处理、添加任务、删除任务、标记任务状态以及清除已完成任务的功能。使用了Ant Design组件库来提升用户界面的质量和一致性。这个实践展示了如何使用React的函数组件和Hooks来管理状态和处理用户输入,这是现代React开发的推荐做法。
评论已关闭