如题,先看看如何使用Material UI的Table表格:
要实现上面这样的表格,定义数据userList如下:
[
{
id: 1,
name: "Kevin",
age: 10,
subject: 5,
state: 1,
},{
id: 2,
name: "John",
age: 15,
subject: 1,
state: 0,
},{
id: 3,
name: "Lily",
age: 20,
subject: 2,
state: 1,
}
]
然后使用方式如下:
<TableContainer component={Paper} variant="outlined">
<Table aria-label="customized table">
<TableHead>
<TableRow>
<TableCell width={80} align="center">No</TableCell>
<TableCell align="center">Name</TableCell>
<TableCell width={180} align="center">age</TableCell>
<TableCell width={180} align="center">subject</TableCell>
<TableCell width={180} align="center">State</TableCell>
<TableCell align="center">Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{userList.map((row, index) => (
<TableRow key={row.id}>
<TableCell align="center" width={80}>{index+1}</TableCell>
<TableCell align="center">{row.name}</TableCell>
<TableCell align="center" width={180}>{row.age}</TableCell>
<TableCell align="center" width={180}>{row.subject}</TableCell>
<TableCell align="center" width={180}>{row.state}</TableCell>
<TableCell align="center">
<Button
variant="outlined"
color="secondary"
onClick={() => { handleDisable(row) }}
>
{row.state == 0 ? "ENABLE" : "DISABLE"}
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
可以看到上面表格每一行的按钮文字,是根据数据 state 来决定的,state为0说明此条数据被禁用了,则按钮显示“ENABLE”,表示点击启用此条数据,反之state为1则显示“DISABLE”,表示点击禁用此条数据。点击事件为handleDisable(),在此代码就不贴了。
我现在有个需求,要求state为0的时候,此行数据背景色要显示为灰色,按钮颜色也要有变化,以和没被禁用的数据显示上区分更明显。预期效果如下:
那么我们这么改:
先定义禁用和未禁用的表格行样式变量:
const disabledTableRow = {
background: "#00000008",
};
const enabledTableRow = {
background: "white",
};
然后把样式设置给TableRow:
即把这一行
<TableRow key={row.id}>
改为下面这样:
<TableRow key={row.id} style={row.state == 0 ? disabledTableRow : enabledTableRow}>
表格行的颜色区分就出来了。至于按钮的颜色区分,把
<Button
variant="outlined"
color="secondary"
onClick={() => { handleDisable(row) }}
>
{row.state == 0 ? "ENABLE" : "DISABLE"}
</Button>
Button的variant属性改一下即可:
<Button
variant={row.state == 0 ? "contained" : "outlined"}
color="secondary"
onClick={() => { handleDisable(row) }}
>
{row.state == 0 ? "ENABLE" : "DISABLE"}
</Button>