效果如下:
点击添加按钮
添加按钮-弹出添加任务
清除按钮-清除所有的已完成和未完成事项
删除按钮-删除选中事项
完成按钮-把选中事项变成完成状态
所有的按钮都做了选中校验
接下来上代码
import React, { useState } from 'react';
import { Checkbox, Button, Input, Space, message, Card, Divider } from 'antd';
const { TextArea } = Input;
export default function TodoList() {
const [todoList, setTodoList] = useState([
'洗脸',
'刷牙',
'吃早餐',
'看书',
'游戏',
]);
const [didList, setDidList] = useState([
'洗脸2',
'刷牙3',
'吃早餐4',
'看书5',
'游戏6',
]);
const [addVisible, setAddVisible] = useState(false);
//仅仅是用来判断某个东西是否展示,只有两种状态,设置Boolean就可以了
const [hasChecked, setHasChecked] = useState([]);
const [text, setText] = useState('');
const submit = () => {
if (!text) {
message.error('请输入任务信息!');
return;
}
// 如果需要判断是否有重复的未做任务
const copy = new Set(todoList.concat([text]));
setTodoList(Array.from(copy));
// 如果不判断
// setTodoList(todoList.concat([text]));
setText('');
setAddVisible(false);
};
const deleteFunc = () => {
if (hasChecked.length === 0) {
message.error('请选择任务!');
return;
}
setHasChecked([]);
setTodoList(todoList.filter((__) => !hasChecked.includes(__)));
};
function clear() {
setTodoList([]);
setDidList([]);
}
function finished() {
if (hasChecked.length === 0) {
message.error('请选择任务!');
return;
}
// 如果需要判断是否有重复的已做任务
const copy = new Set(didList.concat(hasChecked));
setDidList(Array.from(copy));
// 如果不判断
// setDidList(didList.concat(hasChecked));
setHasChecked([]);
setTodoList(todoList.filter((__) => !hasChecked.includes(__)));
}
return (
<>
{
addVisible ? <Card
title="添加任务"
extra={<Space>
<Button onClick={submit}>保存</Button>
<Button onClick={() => setAddVisible(false)}>隐藏</Button>
</Space>}
>
<TextArea
value={text}
allowClear
placeholder="待做···"
autoSize={true}
onChange={({ target: { value } }) => setText(value)}
/>
</Card> : null
}
<Card
title={'React todo list'}
extra={<Space>
<Button onClick={() => setAddVisible(true)}>添加</Button>
<Button onClick={deleteFunc}>删除</Button>
<Button onClick={finished}>完成</Button>
<Button onClick={clear}>清除</Button>
</Space>}
>
<div>
<h5>未完成</h5>
<Checkbox.Group
options={todoList}
onChange={setHasChecked}
/>
</div>
<Divider />
<div>
<h5>已完成</h5>
<Checkbox.Group
value={didList}
options={didList}
disabled
className="checked"
/>
</div>
</Card>
</>
);
}