简体   繁体   English

样式材料 ui 表格单元格根据它们的值

[英]Styling material ui table cells according to their values

I have a material ui table and I would like to colour the different cells according to what value is displayed in them.我有一个材质 ui 表,我想根据其中显示的值为不同的单元格着色。 The cells are populated with json data using map.这些单元格使用地图填充了 json 数据。 For example if a cell has the value 1, I would like the colour to be yellow.例如,如果一个单元格的值为 1,我希望颜色为黄色。

    {
      Name: "A Person",
      Attendence: [
        {
          date: "2019/12/01",
          attendence: 1
        },
        {
          date: "2019/12/02",
          attendence: 1
        },
        {
          date: "2019/12/03",
          attendence: 0
        }
      ]
    }
  ];

  return (
    <Fragment>
      {attendence.map(person => {
        return (
          <Table>
            <thead>
              <tr>
                <th>Name</th>
                {person.Attendence.map(personAttendendance => {
                  return <th>{personAttendendance.date}</th>;
                })}
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>{person.Name}</td>
                {person.Attendence.map(personAttendendance => {
                  return <td>{personAttendendance.attendence}</td>;
                })}
              </tr>
            </tbody>
          </Table>
        );
      })}
    </Fragment>
  );
}

export default Test;

That is what the table looks like.这就是桌子的样子。 I tried我试过

    if(value === 1){
      return(
        <TableCell style={{ background: "red" }}>{value}</TableCell>
      )

    } else {
      return(
        <TableCell style={{ background: "red" }}>{value}</TableCell>
      )
    }

  }

But that did not work .但那没有用。 It just read the else and made everything red.它只是读取其他内容并使所有内容变红。

Change your tbody in test.js to:将 test.js 中的tbody更改为:

<tbody>
   <tr>
      <td>{person.Name}</td>
      {person.Attendence.map(personAttendendance => {
          if(personAttendendance.attendence === 1){
             return <td style={{background: "red" }}>{personAttendendance.attendence}</td>;
          } else {
             return <td style={{background: "blue" }}>{personAttendendance.attendence}</td>;
          }                  
      })}
   </tr>
</tbody>

or或者

<tbody>
   <tr>
      <td>{person.Name}</td>
      {person.Attendence.map(personAttendendance => {
          return <td style={{background: personAttendendance.attendence === 1 ? "red" : "blue"}}>{personAttendendance.attendence}</td>;                
      })}
   </tr>
</tbody>

Which ever suits you best.哪个最适合你。

Link to fork here . 在这里分叉的链接。 (using the second example) (使用第二个例子)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM