基于 react-table-6 中另一列结果的颜色单元格

color cell based on the result of another column in react-table-6

当前我正在显示 table,其中 Protected 列中的单元格如果为真则突出显示为绿色,如果为假则为红色:

Name |     Source     | Protected
________________________________
Ryan      Computer       False
Briana Phone, Computer   True
Shawn      Phone         True
Serge      Phone         False

我对应的代码是这样的:

const columns = [
      {
        Header: "Name",
        accessor: "Name",
        style: {
          textAlign: "center",
        },
      },
      {
        Header: "Source",
        accessor: "Source",
        style: {
          textAlign: "center",
        },
      },
      {
        Header: "Protected",
        id: "Protected",
        accessor: (d) => d.protected.toString(),
        getProps: (state, rowInfo) => {
          if (rowInfo && rowInfo.row) {
            return {
              style: {
                textAlign: "center",
                background: rowInfo.row.protected === "false" ? "red" : "green",
              },
            };
          } else {
            return {};
          }
        },
      },
    ];

是否可以根据相应的 Protected 属性是真还是假,删除 Protected 列并用红色或绿色突出显示 Source 列? 即

Name |     Source (highlighted color)   
_____________________________________
Ryan       Computer  (red)     
Briana     Phone, Computer (green)  
Shawn      Phone (green)      
Serge      Phone (red)       

我的数据是这样的:

[
  {
    "Name": "Ryan",
    "Protected": false,
    "Source": ["Computer"],
  },
  {
    "Name": "Briana",
    "Protected": true,
    "Source": ["Phone, Computer"],
  },
  {
    "Name": "Shawn",
    "Protected": true,
    "Source": ["Phone"],
  },
  {
    "Name": "Serge",
    "Protected": false,
    "Source": ["Phone"],
  }
]

是的,有可能。

为此,在创建列时,您可以使用 Cell 道具影响列的样式,并在数据内容周围添加 <div />

像这样:

columns = [
  {
    Header: "Source",
    accessor: "Source",
    style: {
      textAlign: "center",
    },
    Cell: (row) => {
      return (
        <div style={{ background: row.original.Protected === 'true' ? 'green' : 'red' }}>
          {row.original.Source}
        </div>
      );
    },
  });
];