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

基于React Hooks实现Material UI表格单选/多选复选框功能问题求助

React Hooks + Material UI 表格复选框单选/多选实现方案

核心实现步骤

  • 用useState存储已选中行的ID数组,作为唯一的状态数据源
  • 实现全选逻辑:全选框选中时将所有行ID存入数组,取消选中时清空数组,部分选中时展示半选(indeterminate)状态
  • 实现单行选择逻辑:点击单行复选框时,对应ID已存在则从数组移除,不存在则加入数组

完整代码示例

首先在组件内引入依赖并定义状态:

import { useState } from 'react';
import { Table, TableContainer, TableHead, TableBody, TableRow, TableCell, Checkbox } from '@mui/material';

// 组件内部逻辑
const ExcludedPersons = () => {
  // 此处替换为你实际的head、body数据源即可
  const head = ['ID', '姓名'];
  const body = {
    excluded_persons: [
      {id: 1, name: '张三'},
      {id: 2, name: '李四'},
      {id: 3, name: '王五'}
    ]
  };
  const classes = {}; // 替换为你实际的样式对象

  // 选中状态:存储已选中的行ID数组
  const [selectedIds, setSelectedIds] = useState([]);
  // 所有行的ID数组,用于全选逻辑判断
  const allRowIds = body?.excluded_persons?.map(row => row.id) || [];
  // 全选状态判断
  const isAllSelected = allRowIds.length > 0 && selectedIds.length === allRowIds.length;
  // 半选状态判断:有选中但未全选
  const isIndeterminate = selectedIds.length > 0 && selectedIds.length < allRowIds.length;

  // 全选切换逻辑
  const handleSelectAll = (e) => {
    if (e.target.checked) {
      setSelectedIds(allRowIds);
      return;
    }
    setSelectedIds([]);
  };

  // 单行选择切换逻辑
  const handleSelectOne = (rowId) => {
    if (selectedIds.includes(rowId)) {
      setSelectedIds(selectedIds.filter(id => id !== rowId));
      return;
    }
    setSelectedIds([...selectedIds, rowId]);
  };

  return (
    <TableContainer className={classes.tableContainer}>
      <Table>
        <TableHead className={classes.tableHead}>
          <TableRow>
            <TableCell padding="checkbox">
              <Checkbox
                checked={isAllSelected}
                indeterminate={isIndeterminate}
                onChange={handleSelectAll}
                inputProps={{ "aria-label": "select all desserts" }}
              />
            </TableCell>
            {head.map((el) => (
              <TableCell key={el} align="left">
                {el}
              </TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {body?.excluded_persons?.map((row) => (
            <TableRow key={row.id}>
              <TableCell padding="checkbox">
                <Checkbox 
                  checked={selectedIds.includes(row.id)}
                  onChange={() => handleSelectOne(row.id)}
                />
              </TableCell>
              <TableCell align="left">{row.id}</TableCell>
              <TableCell align="left">{row.name}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

逻辑说明

  • 所有选中状态统一由selectedIds数组管理,避免状态分散导致的不同步问题
  • 半选状态通过indeterminate属性传递给MUI Checkbox组件,自动展示对应样式
  • 如果需要获取选中的完整行数据,可通过body.excluded_persons.filter(row => selectedIds.includes(row.id))直接过滤得到

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 06:39:04