需求: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; }
