javascript MUI V4:如何使用条件行着色

rdlzhqv9  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(89)

我有一个基本的Material UI v4数据网格。我尝试将age为16的任何行更改为全灰色color: 'grey'。我正在努力做到这一点。文档不是很清楚如何更改整个行的字体颜色。这是密码。

import * as React from "react";
import { DataGrid } from "@material-ui/data-grid";

const columns = [
  { field: "id", headerName: "ID", width: 70 },
  { field: "firstName", headerName: "First name", width: 130 },
  { field: "lastName", headerName: "Last name", width: 130 },
  {
    field: "age",
    headerName: "Age",
    type: "number",
    width: 90
  },
  {
    field: "fullName",
    headerName: "Full name",
    description: "This column has a value getter and is not sortable.",
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `${params.getValue("firstName") || ""} ${
        params.getValue("lastName") || ""
      }`
  }
];

const rows = [
  { id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
  { id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
  { id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
  { id: 4, lastName: "Stark", firstName: "Arya", age: 16 }
];

export default function App() {
  const [selectionModel, setSelectionModel] = React.useState([]);
  return (
    <div style={{ height: 400, width: "100%" }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={25}
        checkboxSelection
        hideFooterPagination
        onSelectionModelChange={(newSelection) => {
          setSelectionModel(newSelection.selectionModel);
      }}
      selectionModel={selectionModel}
       
      />
      {selectionModel.map(val =><h1>{val}</h1>)}
    </div>
  );
}

我正在尝试做这样的事情(当然这行不通)

const greyOut = () => {
    const data = row.age
    if (data == 16){
     return (
        <TableRow style={{ color: 'grey'}}>{row}</TableRow>   
    )}
}

有人能帮忙吗?

wz8daaqr

wz8daaqr1#

您可以在<DataGrid/>中使用getRowClassName prop 。这样你就可以应用某些css类到所有符合条件的行。params.row允许您访问行中的所有值。

<DataGrid
    ...
    getRowClassName={(params) => {
      return params.row.age === 16 ? "highlight" : "";
    }}
    ...
  />

现在你可以使用一个经典的css样式表,或者在<DataGrid/>中添加一个额外的sx属性:

<DataGrid
    ...
    sx={{
      ".highlight": {
        bgcolor: "grey",
        "&:hover": {
          bgcolor: "darkgrey",
        },
      },
    }}
  />

相关问题