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

如何在Material UI的TextField选择菜单点击时实现滚动

如何在Material UI的TextField选择菜单中实现滚动?

你可以直接通过TextField的SelectProps传递MenuProps配置来实现滚动效果,无需替换成单独的Select组件,具体实现如下:

修改后的代码

import * as React from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import MenuItem from "@mui/material/MenuItem";

const currencies = [
  {
    value: "USD",
    label: "$"
  },
  {
    value: "EUR",
    label: "€"
  },
  {
    value: "BTC",
    label: "฿"
  },
  {
    value: "JPY1",
    label: "1"
  },
  {
    value: "JPY2",
    label: "2"
  },
  {
    value: "JPY3",
    label: "3"
  },
  {
    value: "JPY4",
    label: "4"
  },
  {
    value: "JPY",
    label: "¥"
  }
];

export default function SelectTextFields() {
  return (
    <Box
      component="form"
      sx={{
        "& .MuiTextField-root": { m: 1, width: "25ch" }
      }}
      noValidate
      autoComplete="off"
    >
      <div>
        <TextField
          id="outlined-select-currency"
          select
          label="Select"
          defaultValue="EUR"
          helperText="Please select your currency"
          // 配置下拉菜单的滚动属性
          SelectProps={{
            MenuProps: {
              sx: {
                maxHeight: 200, // 自定义菜单最大高度
                overflowY: "auto" // 内容超出时显示垂直滚动条
              }
            }
          }}
        >
          {currencies.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </TextField>
      </div>
    </Box>
  );
}

实现原理

TextField开启select模式后,内部实际封装了Select组件。通过SelectProps可以将配置传递给内部的Select,其中MenuProps用于控制下拉菜单的样式:

  • 设置maxHeight限制菜单的最大显示高度
  • 开启overflowY: "auto",当菜单内容高度超过设置的最大值时,自动显示滚动条

内容的提问来源于stack exchange,提问作者Екатерина

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:02:36