根据React中的条件更改表行颜色

时间:2020-05-10 20:41:11

标签: reactjs colors row

我想根据condition更改表行的颜色。

我的代码:

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

                  <TableRow  key={i} >

                    <TableCell component="th" scope="row"  >
                     <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>

                  </TableRow>

                ))}
 </TableBody>

现在我要检查key == null的值,然后行的颜色应该是color1或color2

即类似这样的东西。

if(row.c == null)然后rowcolor = color1;

else rowcolor = color2;

如何做出反应?

1 个答案:

答案 0 :(得分:0)

不适用:您的问题相当模糊,需要进一步说明。

我想您想根据条件设置类,是吗?

您可以使用tarnary运算符根据您的条件设置类名称。

首先,您需要创建两个类。一个是积极的条件,另一个是相反的条件。

然后做类似的事情

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

                  <TableRow  key={i}  >

                    <TableCell component="th" scope="row"  >
                     <Typography variant="h4"> {row.a} </Typography>
                    </TableCell>
                    <TableCell align="left" > <Typography variant="h4">{row.b}</Typography>  </TableCell>
                    <TableCell align="left" > <Typography variant="h4"  style={row.c === null ? 'blue' : 'pink' > {row.c} </Typography> </TableCell>

                  </TableRow>

                ))}
 </TableBody>

const pink = {
background color: 'pink'
}

const blue ={
background color: 'blue'
}

编辑

关于OP所做的说明,我已从className更改为style。