antd中table表格奇偶行设置不同样式(颜色交替)
需求:antd 中Table表格样式做奇偶交替展示,让用户更加明显看出区别
思路:主要使用以下rowClassName,expandedRowClassName属性结合less进行样式的覆盖,渲染时候给奇偶不同类名;
主表属性:rowClassName:(record, index) => index % 2 === 0 ? 'par_blue_even' : 'par_gray_odd'
子表属性:expandedRowClassName:(record, index) => index % 2 === 0 ? 'child_blue_even' : 'child_gray_odd'
less属性:
.hospity-ant-table tr:hover td {
background: transparent !important;
}
组件代码如下:
const HospityTable = React.memo( ({ size = undefined, scroll, styleCross = true, rowKey, columns = [], dataSource = [], rowExpandable = undefined // }: ITableProps) => { // 初始化数据 const [_scroll, _setScroll] = React.useState<ITableProps['scroll']>(undefined); const [_dataSource, _setDataSource] = React.useState<ITableProps['dataSource']>([]); const [_rowExpandable, _setRowExpandable] = React.useState<ITableProps['rowExpandable']>(undefined); React.useMemo(() => { if (scroll) { _setScroll(scroll); } }, [scroll]); React.useMemo(() => { _setDataSource(dataSource); }, [dataSource]); React.useMemo(() => { if (rowExpandable) { _setRowExpandable(rowExpandable); } }, [rowExpandable]); return ( <> <div> <Table size={size} scroll={_scroll} showSorterTooltip={false} columns={columns} rowKey={record => rowKey ? record[rowKey] : record['id'] ?? record['key']} className='hospity-ant-table' rowClassName={styleCross ? ((record, index) => index % 2 === 0 ? 'par_blue_even' : 'par_gray_odd') : undefined} expandable={ _rowExpandable ? { defaultExpandedRowKeys: _rowExpandable.defaultExpandedRowKeys, expandedRowClassName: styleCross ? ((record, index) => index % 2 === 0 ? 'child_blue_even' : 'child_gray_odd') : undefined, expandedRowRender: record => <Table size="small" rowKey="key" columns={_rowExpandable.colunms} dataSource={record[_rowExpandable.source]} pagination={false} /> } : undefined } dataSource={_dataSource} pagination={false} /> </div> </> ); }, );
样式代码如下
.par_blue_even { background: #d9f3ff; td { background-color: #d9f3ff; } } .par_gray_odd { background: #fafafa; td { background-color: #fafafa; } } .child_blue_even { background: #d9f3ff; td { background: transparent !important; .ant-table-thead { tr { th { background-color: #d9f3ff; } } } .ant-table-tbody { background-color: #d9f3ff; } } } .child_gray_odd { background: #fafafa; td { background: transparent !important; .ant-table-thead { tr { th { background-color: #fafafa; } } } .ant-table-tbody { background-color: #fafafa; } } } .hospity-ant-table tr:hover td { background: transparent !important; }