You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为@mui/x-date-pickers的<DatePicker/>组件设置高度?

解决@mui/x-date-pickers
return (<DatePicker/>)
组件高度修改问题

首先,你代码里存在一个核心错误:renderInput的回调函数没有返回组件,导致所有针对TextField的样式设置都不会生效。先修复这个基础问题,再进行样式调整。

修复renderInput的返回问题

你的renderInput回调里仅声明了但未返回,正确写法如下:

import React from "react";
import { DatePicker } from "@mui/x-date-pickers";
import TextField from "@mui/material/TextField";

export default const Component = () => {
  const [value, setValue] = React.useState(null); // 补充缺失的状态定义
  return (
    <DatePicker
      fullWidth
      views={['year', 'month', 'day']}
      openTo="month"
      value={value}
      onChange={(newValue) => setValue(newValue)}
      renderInput={(params) => (
        // 用括号直接返回组件,或显式添加return
        <TextField
          {...params}
          size="small"
        />
      )}
    />
  )
}

有效修改DatePicker高度的方法

方法1:通过TextField的size属性快速调整

MUI的TextField自带size="small"属性,可直接缩小组件整体高度,修复renderInput后即可生效。

方法2:通过TextField的sx自定义精确高度

若需要指定具体高度,可在TextField的sx中设置,同时调整内部输入框的内边距和行高,避免内容错位:

renderInput={(params) => (
  <TextField
    {...params}
    sx={{
      height: '50px',
      '& .MuiInputBase-input': {
        padding: '12px 14px', // 适配高度调整输入框内边距
        lineHeight: 1.2
      }
    }}
  />
)}

方法3:通过DatePicker的slotProps统一配置

无需在renderInput中单独设置,可直接通过DatePicker的slotProps属性针对输入框配置样式:

<DatePicker
  fullWidth
  views={['year', 'month', 'day']}
  openTo="month"
  value={value}
  onChange={(newValue) => setValue(newValue)}
  slotProps={{
    textField: {
      size: "small",
      // 或自定义sx
      sx: { height: '50px', '& .MuiInputBase-input': { padding: '12px 14px' } }
    }
  }}
/>

方法4:全局CSS批量修改

若需要全局调整所有DatePicker的高度,可在全局CSS文件中设置:

/* 针对DatePicker的输入框容器 */
.MuiDatePicker-root .MuiTextField-root {
  height: 50px !important;
}
/* 调整输入框内边距适配高度 */
.MuiDatePicker-root .MuiInputBase-input {
  padding: 12px 14px !important;
}

注意:以上方案完全针对@mui/x-date-pickers中的<DatePicker>组件(自动适配移动端/桌面端),无需切换到DesktopDatePicker或其他变体。

内容的提问来源于stack exchange,提问作者Dark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:10:11