如何為每一行新增可控制的複選框:MUI Datagrid中的實作方法
P粉329425839
P粉329425839 2024-03-29 08:47:07
0
1
413

我知道新增複選框或文字欄位的方法是使用 renderCell 並且它有效,我可以看到複選框:

但是,我不明白應該如何單獨控制每一行的複選框/文字欄位。例如,如果我希望第 1 行具有 TextField 的「填充」變體,而第 2 行具有「輪廓」變體,該怎麼辦?

import * as React from "react";
import {DataGrid} from "@mui/x-data-grid";
import {Box, Checkbox, TextField} from "@mui/material";

const columns = [
  {field: "id", headerName: "ID", width: 30},
  {field: "col1", headerName: "Column 1", width: 150},
  {field: "col2", headerName: "Column 2", width: 150},
  {field: "col3", headerName: "Column 3", width: 150, renderCell: (params) => <Checkbox />},
];

const rows = [
  {id: 1, col1: "Example", col2: "Content", col3: ??????},
  {id: 2, col1: "Example", col2: "Content", col3: ??????},
  {id: 3, col1: "Example", col2: "Content", col3: ??????},
];

export default function Table() {
  return (
    <Box sx={{}}>
      <DataGrid rows={rows} columns={columns} />
    </Box>
  );
}

我嘗試新增一個新的<Checkbox /> ,其中包含諸如<Checkbox defaultChecked/> 之類的道具,但當然,這是行不通的。

P粉329425839
P粉329425839

全部回覆(1)
P粉402806175

請看一下我為您提供的範例。希望我能回答你的問題。 https://codesandbox.io/s/optimistic-leaf-xm32lk ?file=/Demo.tsx

#
import * as React from "react";
import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import Checkbox from "@mui/joy/Checkbox";

function RenderCheckBox(props: GridRenderCellParams<any, boolean>) {
  const [checked, setChecked] = React.useState(props.value); // Initiated react binded value with param from `rows`

  // Handler for user clicks to set checkbox mark or unset it
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked(event.target.checked);
  };
  //The bind for dynamic mark/unmark: checked={checked}
  //The handler for user clicks: onChange={handleChange}
  return (
    <Checkbox
      label="some text"
      size="lg"
      checked={checked} 
      onChange={handleChange} 
    />
  );
}

const columns: GridColDef[] = [
  { field: "id", headerName: "ID", width: 30 },
  { field: "col1", headerName: "Column 1", width: 150 },
  { field: "col2", headerName: "Column 2", width: 150 },
  {
    field: "checked",
    headerName: "Column 3",
    width: 150,
    renderCell: RenderCheckBox
  }
];
// Here 'checked' field will pass the param to component.
const rows = [
  { id: 1, col1: "Example", col2: "Content", checked: true },
  { id: 2, col1: "Example", col2: "Content", checked: false },
  { id: 3, col1: "Example", col2: "Content", checked: false }
];

export default function RenderCellGrid() {
  return (
    <div style={{ height: 300, width: "100%" }}>
      <DataGrid rows={rows} columns={columns} />
    </div>
  );
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!