如何将布尔类型图标更改为相反

How can change boolean type icons to oposite

我想要名为 archive 的空键进行检查并且值为“true”时有线条图标。

示例如下:我想要与列状态相反的内容。不改变 tableIcons.js

这是代码和codesandbox示例:

import React, { useState } from "react";
import { render } from "react-dom";
import MaterialTable from "material-table";
import SaveAltIcon from "@material-ui/icons/SaveAlt";
import tableIcons from "./TableIcons.js";

const rando = max => Math.floor(Math.random() * max);

const rawData = [
  { id: 1111111111, archive: "true", type: "CC" },
  { id: 2222222222, archive: "", type: "RR" },
  { id: 3333333333, archive: "true", type: "CC" },
  { id: 4444444444, archive: "", type: "PS" },
  { id: 5555555555, archive: "true", type: "II" }
];

const columns = [
  { title: "Id", field: "id" },
  { title: "Type", field: "type" },
  { title: "Status", field: "archive", type: "boolean" }
];

const App = () => {
  const [data, setData] = useState(rawData);

  return (
    <MaterialTable
      data={data}
      columns={columns}
      title="Starter Template"
      icons={tableIcons}
    />
  );
};

render(<App />, document.querySelector("#root"));

https://codesandbox.io/s/material-table-starter-template-0s0np?file=/src/index.js

首先我将 archive prop 值从 "true" 修改为 true 以便于条件检查,这样类型是布尔值而不是字符串。

然后我从您已经在使用的依赖项中导入了检查和删除图标:

import { Check, Remove } from "@material-ui/icons";

最后,在定义列 const 的地方,我将一个函数传递给 render prop,如下所示:

render: rowdata =>  rowdata.archive !== true ?  <Check /> : <Remove />

当然,如果需要,您可以更改条件。 Link 到有关此主题 here 的 Material-Table 文档。

这是修改后的代码:

import React, { useState } from "react";
import { render } from "react-dom";
import MaterialTable from "material-table";
import SaveAltIcon from "@material-ui/icons/SaveAlt";
import tableIcons from "./TableIcons.js";
import { Check, Remove } from "@material-ui/icons";

const rando = (max) => Math.floor(Math.random() * max);

const rawData = [
{ id: 1111111111, archive: true, type: "CC" },
{ id: 2222222222, archive: "", type: "RR" },
{ id: 3333333333, archive: true, type: "CC" },
{ id: 4444444444, archive: "", type: "PS" },
{ id: 5555555555, archive: true, type: "II" },
];

const columns = [
{ title: "Id", field: "id" },
{ title: "Type", field: "type" },
{
    title: "Status",
    field: "archive",
    type: "boolean",
    render: (rowdata) => (rowdata.archive !== true ? <Check /> : <Remove />),
    // the ternary expression above is the same as:
    // if (rowdata.archive !== true) {
    //   return <Check />;
    // } else {
    //   return <Remove />;
    // }
},
//
];

const App = () => {
const [data, setData] = useState(rawData);

return (
    <MaterialTable
    data={data}
    columns={columns}
    title="Starter Template"
    icons={tableIcons}
    />
);
};

render(<App />, document.querySelector("#root"));

这里是link到sandbox。我希望这对你有用!