資料格 - 欄位釘選
釘選欄位,使其始終保持可見。
釘選(或凍結、鎖定或黏性)欄位是指在使用者水平捲動資料格時始終可見的欄位。 它們可以釘選在左側或右側,並且無法重新排序。
釘選欄位有幾種方法
初始化釘選的欄位
若要透過 initialState
設定釘選欄位,請將具有以下形狀的物件傳遞給此屬性
interface GridPinnedColumnFields {
left?: string[]; // Optional field names to pin to the left
right?: string[]; // Optional field names to pin to the right
}
以下示範說明了此方法的工作原理
控制釘選的欄位
雖然 initialState
屬性僅適用於在初始化期間設定釘選欄位,但 pinnedColumns
屬性允許您隨時修改釘選哪些欄位。 傳遞給它的值遵循與先前方法相同的形狀。 將其與 onPinnedColumnsChange
一起使用,以了解何時釘選或取消釘選欄位。
停用欄位釘選
針對所有欄位
欄位釘選預設為啟用,但您可以透過設定 disableColumnPinning
屬性輕鬆停用此功能。
<DataGridPro disableColumnPinning />
針對某些欄位
若要停用單一欄位的釘選,請將 GridColDef
中的 pinnable
屬性設定為 false
。
<DataGridPro columns={[{ field: 'id', pinnable: false }]} /> // Default is `true`.
以程式設計方式釘選不可釘選的欄位
可能需要允許以程式設計方式釘選或取消釘選一個或多個在 UI 上無法釘選或取消釘選的欄位(即屬性 disableColumnPinning = true
或 colDef.pinnable = false
的欄位)。 這可以透過以下方式之一完成。
- (A) 初始化釘選的欄位
- (B) 控制釘選的欄位
- (C) 使用 API 方法
setPinnedColumns
設定釘選的欄位
// (A) Initializing the pinning
<DataGridPro
disableColumnPinning
initialState={{ pinnedColumns: { left: ['name'] } }}
/>
// (B) Controlling the pinned columns
<DataGridPro
disableColumnPinning
pinnedColumns={{ left: ['name'] }}
/>
// (C) Using the API method `setPinnedColumns` to set the pinned columns
<React.Fragment>
<DataGridPro disableColumnPinning />
<Button onClick={() => apiRef.current.setPinnedColumns({ left: ['name'] })}>
Pin name column
</Button>
</React.Fragment>
以下示範使用方法 (A) 初始化釘選欄位的狀態,即使釘選功能已停用,也會釘選欄位 name
。
釘選核取方塊選取欄位
若要釘選使用 checkboxSelection
時新增的核取方塊欄位,請將 GRID_CHECKBOX_SELECTION_COL_DEF.field
新增至釘選欄位清單。
與動態列高一起使用
您可以同時啟用釘選欄位和 動態列高。 但是,如果列在初始計算後變更其內容,您可能需要觸發手動重新計算以避免不正確的測量。 您可以透過在每次內容變更時呼叫 apiRef.current.resetRowHeights()
來執行此操作。
以下示範包含同時啟用這兩個功能的範例