如何基于React中的3种条件更改表行颜色

问题描述 投票:0回答:2

我是新来的人。我想根据某些条件更改表行。就像我有一个名为deadLine的值。因此,如果DeadLine日期和当前日期之间的差为2,则表行应为绿色;如果差为1,则表行应为黄色;如果为0或-ve,则表行应为红色。

注意:deadLine是格式为dd / MM / yyyy的字符串

我如何才能做到这一点?我在stackOverflow中看到了一些示例,但没有帮助。

我有这样的代码

<TableBody>
                {
                this.props.result.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row,i) =>(


                  <TableRow  key={i} >

                    <TableCell component="th"   >
                     <Typography variant="h4"> {row.a} </Typography>
                    </TableCell>
                    <TableCell align="left" > <Typography variant="h4">{row.b}</Typography>  </TableCell>
                    <TableCell align="left" > <Typography variant="h4"> {row.c} </Typography> </TableCell>
                    <TableCell align="left" > <Typography variant="h4"> {row.d} </Typography> </TableCell>
                    <TableCell align="left" > <Typography variant="h4"> {row.deadline} </Typography> </TableCell>
                  </TableRow>


                ))}
</TableBody>
reactjs tablerow
2个回答
0
投票

首先,定义样式的CSS

.green {} // green style
.yellow {} // yellow style
.red{} // red style

然后定义组件的逻辑方法

.....
dateDiff = (deadLine) => {
  return (Date.parse(deadLine) - Date.now()) / (24 * 60 * 60 * 1000);
}
rowColor = (deadline) => {
   if (this.dateDiff(deadline) >= 2) {
      return 'green';
   } else if (this.dateDiff(deadline) >= 1) {
      return 'yellow';
   } else {
      return 'red';
   }
}
.....
render(){
 ......
 <TableBody>
{
this.props.result.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((row,i) =>(


<TableRow className={this.rowColor(row.deadline)}  key={i} >

  <TableCell component="th"   >
    <Typography variant="h4"> {row.a} </Typography>
  </TableCell>
  <TableCell align="left" > <Typography variant="h4">{row.b}</Typography>  </TableCell>
  <TableCell align="left" > <Typography variant="h4"> {row.c} </Typography> </TableCell>
  <TableCell align="left" > <Typography variant="h4"> {row.d} </Typography> </TableCell>
  <TableCell align="left" > <Typography variant="h4"> {row.deadline} </Typography> </TableCell>
</TableRow>


))}

}


0
投票

您可以只在TableRow上应用类或样式属性:

[<TableRow style={{backgroundColor:'red'}}>将更改您的行的背景。

最好使用类,因此请在css文件中定义三个类:

.green{background-color: green;}
.yellow{background-color: yellow;}
.red{background-color: red;}

然后,您可以创建一个函数,该函数将根据截止日期返回您需要应用的类。像:

const getBackgroundColor = deadline => {
    return conditionToRed ? 'red' : conditionToYellow ? 'yellow' : 'green';
}

在您的jsx中,您将执行类似::>

<TableRow className={getBackgroundColor()}>
    
© www.soinside.com 2019 - 2024. All rights reserved.