You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React实现Table行Checkbox选中/取消选中的handleSelectUser函数逻辑

解决方案:实现表格复选框的选中/取消逻辑

你可以这样编写handleSelectUser函数,通过判断当前用户ID是否已在选中列表中来实现添加或移除操作:

const handleSelectUser = (userId) => {
  setSelectedUserIds(prevIds => {
    // 检查当前ID是否已被选中
    if (prevIds.includes(userId)) {
      // 已选中则移除
      return prevIds.filter(id => id !== userId);
    } else {
      // 未选中则添加
      return [...prevIds, userId];
    }
  });
};

逻辑说明:

  • 使用函数式更新(setSelectedUserIds(prevIds => ...))确保每次更新都基于最新的状态值,避免因闭包导致的状态不一致问题。
  • 通过includes()判断用户ID是否在选中数组中,比indexOf()更直观简洁。
  • 移除操作使用filter()返回不包含当前ID的新数组;添加操作则通过扩展运算符创建新数组并加入当前ID。

优化后的完整代码示例:

import { useState } from 'react';
import { TableBody, TableRow, TableCell, Checkbox } from '@mui/material'; // 假设使用Material UI

const YourComponent = ({ users }) => {
  const [selectedUserIds, setSelectedUserIds] = useState([]);

  const handleSelectUser = (userId) => {
    setSelectedUserIds(prevIds => {
      if (prevIds.includes(userId)) {
        return prevIds.filter(id => id !== userId);
      } else {
        return [...prevIds, userId];
      }
    });
  };

  return (
    <TableBody>
      {users.map((user) => (
        <TableRow key={user.id}>
          <TableCell padding="checkbox">
            <Checkbox
              checked={selectedUserIds.includes(user.id)}
              onChange={() => handleSelectUser(user.id)}
              value="true"
            />
          </TableCell>
          <TableCell>{user.email}</TableCell>
          <TableCell>{user.roles}</TableCell>
          <TableCell>{user.status}</TableCell>
        </TableRow>
      ))}
    </TableBody>
  );
};

export default YourComponent;

内容的提问来源于stack exchange,提问作者linda boufi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:35:19