reactjs MUI Datagrid:如何添加一个可由每行控制的复选框?

bzzcjhmw  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(71)

我知道添加复选框或TextField的方法是使用renderCell,它可以工作,我可以看到复选框:
x1c 0d1x的数据
然而,我不明白我应该如何单独控制每行的Checkbox/TextField。比如,如果我想让第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/>这样的 prop ,但是当然,这不起作用。

mbskvtky

mbskvtky1#

请看我的例子。希望我能回答你的问题。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>
  );
}

字符串

相关问题