react antd checkbox实现全选,多选

背景

目前好像只有table组件有实现表格数据的全选功能,如果说对于list,card,collapse等其他组件来说,需要自己结合checkbox来手动实现全选功能。

Checkbox.Group有实现全选功能,但是对于需要遍历出来的数据(接口动态返回),这种方式不太可行。

在这里插入图片描述

方案

考虑都使用checkbox组件来实现,同时增加状态管理。

1、增加一个【全选】checkbox,同时遍历每一行数据的时候,为Panel组件的header属性添加checkbox选择框。

<Checkbox
  indeterminate={indeterminate}
  checked={checkAll}
  onChange={handleClickAllCheckbox}
>
  全选
</Checkbox>

const renderPanelItem = () => {
  return caseList?.map((item: CaseItem) => {
    const key = item.replay_id;
    const isChecked = selectedRowKeys?.includes(item.task_record_id); // 判断是否勾选
    return (
      <Panel
        header={
          <>
            <Checkbox
              style={{ marginRight: 5 }}
              onChange={(e) => {
                e.stopPropagation();
                handleClickItemCheckbox(isChecked, item.task_record_id);
              }}
              checked={isChecked} // 视图
            />
            <CloseCircleTwoTone twoToneColor="#f5222d" style={{ marginRight: 5 }} />
            <span>{item.task_case_name}</span>
          </>
        }
        key={key}
        extra={renderPanelExtra(item)}
      >
      // ...
      </Panel>
    );
  });
};

2、增加需要的状态

  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]); // 勾选的每一行数据的id集合
  const [indeterminate, setIndeterminate] = useState(false); // 【全选】checkbox
  const [checkAll, setCheckAll] = useState(false); // 【全选】checkbox

3、当点击【全选】checkbox的时候

  • 全部勾选:把当前页的item.id和已有的selectedRowKeys一起存起来,注意id去重
  • 取消全部勾选:setSelectedRowKeys([])
  • 同时改变checkAll的状态
  const handleClickAllCheckbox = () => {
    if (!checkAll) {
      setSelectedRowKeys(
        Array.from(new Set([...selectedRowKeys, ...(caseList?.map((item: CaseItem) => item.task_record_id) || [])])),
      );
    } else {
      setSelectedRowKeys([]);
    }
    setCheckAll(!checkAll);
    setIndeterminate(false); // 全选/全不选的indeterminate为false,部分选上才为true
  };

4、当点击【每一行数据的checkbox】的时候

  • 首选需要判断该行数据是否已经被勾选上:const isChecked = selectedRowKeys?.includes(item.task_record_id);
  • 如果已经被勾选上了,说明需要取消勾选,则从selectedRowKeys去除掉该id;否则,为selectedRowKeys添加上该id。
  • 考虑分页的时候,selectedRowKeys需要存放 上一页已勾选的id 和 当前页已勾选的id
  • 然后再用 当前页已勾选的id列表 去判断 checkAll 和 indeterminate【全选checkbox】的状态值
// 获取当前页已勾选的keys
const getCurrentCheckedList = (allKeys: number[], allData: CaseItem[]) => {
  const current: number[] = [];
  allKeys?.forEach((checkedId) => {
    allData?.forEach((c: CaseItem) => {
      if (c.task_record_id === checkedId) {
        current.push(checkedId);
      }
    });
  });
  return current;
};

// 点击每一项数据前面checkbox时
const handleClickItemCheckbox = (isChecked: boolean, taskRecordId: number) => {
  let keys;
  if (isChecked) {
    keys = selectedRowKeys.filter((id) => id !== taskRecordId);
  } else {
    keys = [...selectedRowKeys, taskRecordId];
  }
  setSelectedRowKeys(keys);
  
  // 更新全选checkbox的状态值
  const current = getCurrentCheckedList(keys, caseList);
  setCheckAll(current?.length === limit); // limit表示每一页展示的数量,checkAll是否为true也只是针对当前页来说
  setIndeterminate(!!current.length && current.length < limit);
};
  • 另外,在进行翻页请求数据的时候,需要对当前页的checkAll状态值进行判断,并初始化
        // 当翻页时,初始化【全选】选项
        const currentPageCheckedList = getCurrentCheckedList(selectedRowKeys, resp_list); // resp_list表示接口返回的数据
        setCheckAll(currentPageCheckedList?.length === limit);
        setIndeterminate(!!currentPageCheckedList.length && currentPageCheckedList.length < limit);

效果图:
在这里插入图片描述

参考文档:antd CheckBox实现全选、多选antd checkbox全选

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值