資料格 - 樣式
網格 CSS 可以輕鬆覆寫。
使用 sx
屬性
對於一次性樣式,可以使用 sx
屬性。它允許直接對資料格元素應用從簡單到複雜的自訂。接受的鍵可以是任何 CSS 屬性以及 MUI 提供的自訂屬性。有關更多詳細資訊,請訪問 sx
屬性頁面。
<DataGrid sx={{ m: 2 }} /> // Sets the margin to 2 times the spacing unit = 16px
按下 Enter 鍵開始編輯
樣式化欄標題
GridColDef
類型具有在標題上應用類別名稱和自訂 CSS 的屬性。
headerClassName
:將類別名稱應用於欄標題。它也可以是一個函數,該函數使用GridColumnHeaderParams
物件調用。headerAlign
:對齊標題的內容。它必須是 'left' | 'right' | 'center'。
const columns: GridColDef[] = [
{
field: 'first',
headerClassName: 'super-app-theme--header',
headerAlign: 'center',
},
{
field: 'last',
headerClassName: 'super-app-theme--header',
headerAlign: 'center',
},
];
按下 Enter 鍵開始編輯
樣式化列
可以使用 getRowClassName
屬性在每列上應用自訂 CSS 類別。它使用 GridRowParams
物件調用,並且必須傳回一個字串。有時可能需要使用更高優先順序的 CSS 選擇器來覆寫現有規則。
interface GridRowParams<R extends GridRowModel = GridRowModel> {
/**
* The grid row id.
*/
id: GridRowId;
/**
* The row model of the row that the current cell belongs to.
*/
row: R;
/**
* All grid columns.
*/
columns: GridColDef[];
}
按下 Enter 鍵開始編輯
樣式化儲存格
有多種方法可以在儲存格上應用自訂 CSS 類別。
- 使用
GridColDef
的cellClassName
屬性
此屬性允許設定一個 CSS 類別,該類別應用於定義它的欄的每個儲存格。它也可以是一個函數,該函數使用 GridCellParams
物件調用。
const columns: GridColDef[] = [
{
field: 'name',
cellClassName: 'super-app-theme--cell',
},
{
field: 'score',
type: 'number',
cellClassName: (params: GridCellParams<number>) =>
clsx('super-app', {
negative: params.value < 0,
positive: params.value > 0,
}),
},
];
- 使用
getCellClassName
屬性
此屬性針對每欄中的每個儲存格調用。與第一個選項不同,此屬性在資料格層級而不是欄層級定義。它也使用 GridCellParams
物件調用。
按下 Enter 鍵開始編輯
儲存格對齊
使用 GridColDef
中的 align
屬性來變更儲存格內容的對齊方式。從以下值中選擇一個:'left' | 'right' | 'center'。
條紋列
您可以使用傳遞給 getRowClassName
的 indexRelativeToCurrentPage
參數,將交替樣式應用於列。
以下示範說明了如何實現這一點。
按下 Enter 鍵開始編輯
主題標題和釘選區塊
預設情況下,資料格對其標題和釘選區塊的背景使用 Material UI theme.palette.background.default
顏色。這些元素需要純色來隱藏它們後面的可捲動內容。您可以使用以下配置覆寫該顏色
import { createTheme } from '@mui/material/styles';
import type {} from '@mui/x-data-grid/themeAugmentation';
const theme = createTheme({
mixins: {
MuiDataGrid: {
// Pinned columns sections
pinnedBackground: '#340606',
// Headers, and top & bottom fixed rows
containerBackground: '#343434',
},
},
});
自訂主題
以下示範利用 CSS 自訂 API 來符合 Ant Design 規範。