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

如何隐藏Material React Table选择列表头(保留行选择功能)

问题解决:隐藏Material React Table选择列表头,保留行选择功能

问题

需要保留行选择功能,但隐藏带单选按钮的选择列表头。尝试通过initialState.columnVisibility设置mrtSelectRow: false无效。

解决方案

mrtSelectRow是Material React Table内置的特殊选择列,无法通过常规的列可见性配置隐藏表头。正确做法是通过selectColumnOptions配置项直接关闭选择列的表头显示:

  • 添加selectColumnOptions={{ enableHeader: false }}到MaterialReactTable组件属性中,即可隐藏选择列的表头,同时保留行选择、行内单选按钮以及行点击选择的功能。

修改后的完整代码

import { useMemo, useState } from "react";
import { MaterialReactTable } from "material-react-table";
import { Box, Badge, Snackbar, Alert } from "@mui/material";
import { updateDeviceByID } from "data/sensors";

const SensorTable = ({ deviceData, setDeviceData, setSelectedDevice }) => {
  const [openSaveAlert, setOpenSaveAlert] = useState(false);
  const [rowSelection, setRowSelection] = useState({});

  const columns = useMemo(
    () => [
      {
        id: "sensors",
        header: "Sensors",
        columns: [
          {
            accessorKey: "name",
            header: "Device Name",
          },
          {
            accessorKey: "description",
            header: "Description",
          },
          {
            accessorKey: "brand",
            header: "Brand",
            enableEditing: false,
          },
          {
            accessorFn: (row) => `${row.coordinates.longitude}`,
            id: "coordinates lng",
            header: "Coordinates Longitute",
          },
          {
            accessorFn: (row) => `${row.coordinates.latitude}`,
            id: "coordinates lat",
            header: "Coordinates Latitude",
          },
          {
            accessorFn: (row) => `${row.status}`,
            id: "status",
            header: "Status",
            size: 100,
            enableEditing: false,
            Cell: ({ row }) => (
              <Box sx={{ display: "flex", alignItems: "center" }}>
                <Badge
                  style={{
                    backgroundColor: row.original.status,
                    width: "20px",
                    height: "20px",
                    borderRadius: "50%",
                  }}
                  overlap="circular"
                  badgeContent=" "
                ></Badge>
              </Box>
            ),
          },
        ],
      },
    ],
    []
  );

  const handleSaveRow = async ({ exitEditingMode, row, values }) => {
    let newDeviceData = JSON.parse(JSON.stringify(deviceData));

    let update = {};

    for (let i = 0; i < newDeviceData.length; i++) {
      if (newDeviceData[i].device_id === row.original.device_id) {
        newDeviceData[i].device_id = row.original.device_id;
        newDeviceData[i].name = values?.name;
        newDeviceData[i].description = values.description;
        newDeviceData[i].brand = values.brand;
        newDeviceData[i].status = row.original.status;
        newDeviceData[i].coordinates = {
          longitude: parseFloat(values["coordinates lng"]),
          latitude: parseFloat(values["coordinates lat"]),
        };
        update = {
          name: values.name,
          description: values.description,
          coords: {
            lng: parseFloat(values["coordinates lng"]),
            lat: parseFloat(values["coordinates lat"]),
          },
        };
      }
    }

    updateDeviceByID(row.original.device_id, update).then((data) => {
      setOpenSaveAlert(true);
    });
    setDeviceData(newDeviceData);
    exitEditingMode();
  };

  const handleSaveDialogClose = () => {
    setOpenSaveAlert(false);
  };

  if (!deviceData) return null;

  return (
    <>
      <Snackbar
        open={openSaveAlert}
        autoHideDuration={4000}
        onClose={handleSaveDialogClose}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
      >
        <Alert onClose={handleSaveDialogClose} severity="success">
          Saved succesfully
        </Alert>
      </Snackbar>
      <MaterialReactTable
        columns={columns}
        data={deviceData}
        editingMode="modal"
        enableEditing
        enableColumnActions={false}
        enableColumnFilters={false}
        enableSorting={false}
        enableTopToolbar={false}
        onEditingRowSave={handleSaveRow}
        enableRowActions
        onRowSelectionChange={setRowSelection}
        state={{ rowSelection }}
        enableMultiRowSelection={false}
        enableRowSelection
        muiTableBodyCellProps={({ row, cell, table }) => ({
          onClick: (event) => {
            console.log(row.original.device_id);
            setSelectedDevice(row.original.device_id);
          },
        })}
        muiTableBodyRowProps={({ row }) => ({
          onClick: row.getToggleSelectedHandler(),
          sx: { cursor: 'pointer'},
        })}
        // 配置隐藏选择列表头
        selectColumnOptions={{ enableHeader: false }}
        initialState={{
          columnVisibility: {
            brand: false,
            description: false,
            "coordinates lat": false,
            "coordinates lng": false,
          },
        }}
      />
    </>
  );
};

export default SensorTable;

说明

  • 移除了initialState.columnVisibility中的mrtSelectRow: false,因为该配置对内置选择列的表头无效
  • 添加selectColumnOptions={{ enableHeader: false }}后,选择列的表头会被隐藏,而行内的单选按钮、行点击选择功能依然保留

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:55:55