【问题标题】:color cell based on the result of another column in react-table-6基于 react-table-6 中另一列结果的颜色单元格
【发布时间】:2020-11-17 19:07:20
【问题描述】:

当前我正在显示表格,其中 Protected 列中的单元格在 True 时以绿色突出显示,如果为 False 则以红色突出显示:

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"],
  }
]

【问题讨论】:

    标签: javascript reactjs react-table react-table-v6


    【解决方案1】:

    是的,有可能。

    为此,在创建列时,您可以使用 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>
          );
        },
      });
    ];
    

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2018-02-13
      • 2012-11-02
      • 1970-01-01
      • 2019-09-23
      相关资源
      最近更新 更多