React项目中设置antd中的table的行列的背景色
1. 示例代码
- 准备一个.css文件
文件名:selectDispatchModel.css
.first-row-bg {
background-color: #fafafa; /* 表头的背景色 */
}
.busy-row-bg {
background-color: #fafafa; /* 繁忙的背景色 */
}
.free-row-bg {
background-color: #f0f0f0; /* 空闲的背景色 */
}
- 准备一个.jsx文件
文件名:selectDispatchModel.jsx
import 'selectDispatchModel.css'
import React from 'react';
import { Table } from 'antd';
const SelectDispatchModel = (props, ref) => {
const data =[
//表格数据来自后端
]
//表格列名和规则设计
const columns = [
{
key: 'name',
title: '引航员', //列名
dataIndex: 'name',
align: 'center',
className: 'table_font'
},
{
title: "状态", //列名
dataIndex: 'pilotState',
key: 'pilotState',
align: 'center',
className: "table_font",
//这里是对"状态"这一列进行设计,text表示状态这一列的文本内容。
render: (text) => {
//如果状态是“繁忙”,就显示为红色。这里也可以修改背景色
return text === "繁忙" ?
<div style={{ color: 'red' }}>{text}</div> : <div>{text}</div>
}
}
]
const rowClassName = (record, index) => {
//record表示表中每一行的内容,index表示行数的索引,从0开始,0表示表头,1是第一行,2是第二行...。
//这里可以控制每一行显示的背景色
if (record.state === 1) {
return 'busy-row-bg'
} else if (record.state === 0) {
return 'free-row-bg'
} else if (index === 0) { //给表头上色
return 'first-row-bg'
}
}
return (
<Table
dataSource={data} //你的表格数据(一般来自后端)
rowClassName={rowClassName}
columns={columns} //表格列名和规则设计
/>
);
}
export default SelectDispatchModel;
2. 调试效果
结果评论:整列中繁忙字体就是红色,空闲就是黑色。上述数字就是代表index. 繁忙和空闲的整行背景色也不同。