我正在try 使用Style函数设置Select MUI组件的样式.因为我想在以后分享这种风格,所以我不想继续使用SX.我try 了几种方法,但我没有找到合适的类来直接从带样式的函数中定位Paper

// Styled 
export const StyledSelect = styled(Select)<SelectProps>(({ theme }) => ({
  textAlign: 'start',
  margin: '5px',
  fontWeight: 800,
  
  '& .MuiSelect-select': {
    // List
    '& .MuiList-root': {
      color: 'green',
      backgroundColor: 'red',
    },
    // Paper 
    '& .MuiMenu-paper': {
      backgroundColor: 'red',
    },
  },
})

// Component
<FormControl>
  <StyledSelect
  variant={variant}
  labelId='select-label'
  // This works 100%
  // MenuProps={{
  //   PaperProps: {
  //     sx: {
  //       backgroundColor: 'transparent',
  //       backdropFilter: 'blur(10px)',
  //     },
  //   },
  // }}
  name={name}
  disabled={disabled}
  value={value}

  onChange={onChangeFn}
  displayEmpty
  >
  </StyledSelect>
</FormControl>

推荐答案

默认Select中的MUIPaper作为样式化组件一直比较难处理,因为Paper属于Select‘S DOM层次 struct 之外(由于它使用了Portal).为了设置它(和Select)的样式,您首先需要设置Select的样式,然后使用样式设置为SelectSelect作为设置Paper样式的基础组件.例如:

const BaseSelect = styled(Select)(({ theme }) => ({
  backgroundColor: "green", // Added just for the example
  textAlign: 'start',
  margin: '5px',
  fontWeight: 800,
}));

// To style the Menu Paper
const StyledSelect = styled(({ className, ...props }: SelectProps) => (
  <BaseSelect {...props} MenuProps={{ PaperProps: { className } }} />
))(({ theme }) => ({
  backgroundColor: "red", // Added just for the example
  // backgroundColor: "transparent",
  backdropFilter: "blur(10px)"
}));

...

// Use as you normally would
// <StyledSelect ... >

Working CodeSandbox:https://codesandbox.io/s/styled-mui-select-and-paper-2dmpct?file=/demo.tsx

Css相关问答推荐

此css Select 器的总体特性是什么?按钮:不是(#mainBtn,.cta)

如何在容器查询体中重新定义:Root的CSS自定义属性值?

设置ScaleImageButton的样式

使用 Vuetify 的 sass 变量时出错

显示 P 元素中加载数据的空行

我可以拆分我的 CSS / SASS webpack 加载器规则,还是它们需要成为一个大规则?

如何阻止 Mud Blazor MudTable 列扩展以适合文本

使 MUI 自动完成打断长词以适合布局

网格区域即使使用 fr 也不会减小其宽度

Angular (13) material - 覆盖 CSS 文件不起作用

在嵌套的弹性框中创建弹性项目之间的空间

Rails 7引擎如何使未编译的样式表可用于托管应用程序?

CSS 中的区域类似于 C# 区域?

如何创建一个与 Bootstrap 3 配合得很好的粘性页脚

内联块在 Internet Explorer 7、6 中不起作用

如何在 CSS 中控制列表样式类型光盘的大小?

如何在 javascript 中获取 HTML 元素的样式值?

让 div 扩展全高

对象拟合不影响图像

如何重置或覆盖 IE CSS 过滤器?