跳到主要內容
+

自訂版面配置

日期與時間選擇器讓您可以重新組織版面配置。

預設版面配置結構

預設情況下,選擇器由以下順序的 5 個子組件組成

  • 工具列顯示選定的日期。可以使用 slotProps: { toolbar: { hidden: false } } 屬性強制顯示。
  • 快捷方式允許快速選擇某些值。可以使用 slotProps.shortcuts 新增
  • 內容顯示當前視圖。可以是日曆或時鐘。
  • 分頁允許在日期時間選擇器中切換日期和時間視圖。可以使用 slotProps: { tabs: { hidden: false } } 屬性強制顯示。
  • 操作欄允許一些互動。可以使用 slotProps.actionBar 屬性新增。

預設情況下,contenttabs 包裹在 contentWrapper 中,以簡化版面配置。

您可以使用 slotsslotProps 自訂這些組件

方向

切換版面配置可以通過在 'portrait''landscape' 之間更改 orientation 屬性值來實現。

以下是以彩色邊框概述的 3 個主要區塊的示範。


選擇日期

––

版面配置結構

<PickersLayoutRoot /> 包裹所有子組件以提供結構。預設情況下,它會渲染一個具有 display: griddiv。這樣所有子組件都放置在 3x3 的 CSS grid 中。

<PickersLayoutRoot>
  {toolbar}
  {shortcuts}
  <PickersLayoutContentWrapper>
    {tabs}
    {content}
  </PickersLayoutContentWrapper>
  {actionBar}
</PickersLayoutRoot>

CSS 自訂

若要移動元素,您可以使用 gridColumngridRow 屬性覆寫其在版面配置中的位置。

在下一個範例中,操作欄被列表取代,然後放置在內容的左側。這是通過應用 { gridColumn: 1, gridRow: 2 } 樣式實現的。

選擇日期

––

  • 接受
  • 清除
  • 取消
  • 今天
按下 Enter 鍵開始編輯

DOM 自訂

重要的是要注意,通過使用 CSS 修改版面配置,新的位置可能會導致視覺渲染和 DOM 結構之間的不一致。在先前的示範中,分頁順序被破壞,因為操作欄出現在日曆之前,而在 DOM 中,操作欄仍然在之後。

若要修改 DOM 結構,您可以建立自訂的 Layout 包裝器。使用 usePickerLayout Hook 取得子組件 React 節點。然後您可以完全自訂 DOM 結構。

import {
  usePickerLayout,
  PickersLayoutRoot,
  pickersLayoutClasses,
  PickersLayoutContentWrapper,
} from '@mui/x-date-pickers/PickersLayout';

function MyCustomLayout(props) {
  const { toolbar, tabs, content, actionBar } = usePickerLayout(props);

  // Put the action bar before the content
  return (
    <PickersLayoutRoot className={pickersLayoutClasses.root} ownerState={props}>
      {toolbar}
      {actionBar}
      <PickersLayoutContentWrapper className={pickersLayoutClasses.contentWrapper}>
        {tabs}
        {content}
      </PickersLayoutContentWrapper>
    </PickersLayoutRoot>
  );
}

以下是完整的範例,其中包含針對 Tab 鍵順序的修復以及新增至版面配置的外部元素。請注意 pickersLayoutClassesPickersLayoutRootPickersLayoutContentWrapper 的使用,以避免重寫預設 CSS。

選擇日期

––

  • 接受
  • 清除
  • 取消
  • 今天

API

請參閱以下文件,以取得此處提及的組件可用的所有屬性和類別的完整參考。