自定义布局
日期和时间选择器允许您重新组织布局。
默认布局结构
默认情况下,选择器由以下顺序排列的 5 个子组件构成
- 工具栏显示选定的日期。可以使用
slotProps: { toolbar: { hidden: false } }
属性强制显示。 - 快捷方式允许快速选择某些值。可以使用
slotProps.shortcuts
添加 - 内容显示当前视图。可以是日历或时钟。
- 标签页允许在日期时间选择器中切换日期和时间视图。可以使用
slotProps: { tabs: { hidden: false } }
属性强制显示。 - 操作栏允许一些交互。可以使用
slotProps.actionBar
属性添加。
默认情况下,content
和 tabs
被包裹在 contentWrapper
中以简化布局。
您可以通过使用 slots
和 slotProps
单独自定义这些组件。
方向
切换布局可以通过将 orientation
属性值在 'portrait'
或 'landscape'
之间更改来实现。
这是一个演示,其中 3 个主要区块用彩色边框勾勒出来。
2025 年 3 月
日一二三四五六
布局结构
<PickersLayoutRoot />
包装所有子组件以提供结构。默认情况下,它渲染一个带有 display: grid
的 div
。 这样所有子组件都放置在 3x3 的 CSS grid 中。
<PickersLayoutRoot>
{toolbar}
{shortcuts}
<PickersLayoutContentWrapper>
{tabs}
{content}
</PickersLayoutContentWrapper>
{actionBar}
</PickersLayoutRoot>
CSS 自定义
要移动元素,您可以使用 gridColumn
和 gridRow
属性覆盖其在布局中的位置。
在下一个示例中,操作栏被列表替换,然后放置在内容的左侧。 这是通过应用 { gridColumn: 1, gridRow: 2 }
样式实现的。
2025 年 3 月
日一二三四五六
- 接受
- 清除
- 取消
- 今天
按 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>
);
}
这是一个完整的示例,修复了制表符顺序问题,并在布局中添加了一个外部元素。 请注意使用 pickersLayoutClasses
、PickersLayoutRoot
和 PickersLayoutContentWrapper
以避免重写默认 CSS。
- 接受
- 清除
- 取消
- 今天
2025 年 3 月
日一二三四五六