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

使用Styled自定义MUI TextField下拉列表样式无效,如何解决?

解决MUI TextField选择列表背景样式不生效的问题

问题原因

你用& .MuiList-root的方式无法生效,是因为TextField的下拉列表(List)是通过Portal渲染在DOM的独立层级(通常是body标签下),不属于TextField组件的DOM树后代,所以后代选择器无法命中目标元素。

解决方案

通过styled组件封装TextField时,利用attrs方法预设SelectProps和MenuProps,直接对下拉列表的容器样式进行定制,代码如下:

import { TextField } from '@mui/material';
import { styled } from '@mui/material/styles';

const StyledSelectTextField = styled(TextField).attrs({
  // 预设Select组件的属性,配置下拉菜单样式
  SelectProps: {
    MenuProps: {
      sx: {
        // 直接设置下拉菜单容器的背景色,List会继承该样式
        backgroundColor: 'white',
        // 如果需要单独定制List的样式,可使用下面的选择器
        '& .MuiList-root': {
          backgroundColor: 'white',
          // 可添加其他List样式,比如padding、字体等
        }
      }
    }
  }
})({
  // 这里可以定制TextField本身的样式,比如输入框边框、字体等
  '& .MuiOutlinedInput-root': {
    borderRadius: 2,
  }
});

// 使用示例
<StyledSelectTextField
  select
  label="选择项"
  defaultValue=""
  options={[
    { value: '1', label: '选项1' },
    { value: '2', label: '选项2' }
  ]}
/>

补充说明

  • 如果只需要设置背景色,直接给MenuProps.sx设置backgroundColor即可,因为MUI的下拉菜单容器(MuiMenu-paper)的背景会被List继承,无需单独设置List的样式。
  • 这种方式完全通过styled组件完成样式封装,使用时不需要额外传递样式属性,符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:45:34