如何在不使用 sx 道具的情况下从选择样式中定位 mui paper 组件?

问题描述 投票:0回答:2

我正在尝试使用 styled 函数来设置 Select MUI 组件的样式。由于我想稍后分享这个风格,所以我不想继续使用sx。我尝试了几种方法,但我缺少正确的类,无法直接从样式函数内定位论文

// 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>

css reactjs typescript material-ui
2个回答
1
投票

默认

Paper
中的 MUI
Select
一直是一个比较棘手的样式组件,因为
Paper
位于
Select
的 DOM 层次结构之外(因为它使用了门户)。为了设置它(和
Select
)的样式,您首先需要设置
Select
的样式,然后使用该样式的
Select
作为设置
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 ... >

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


1
投票

我们在使用

styled-components
定位子类来创建基础组件时遇到了类似的问题。有时您想要定位多个子组件。这有点棘手。对于
Autocomplete
DatePicker
等组件,您也会遇到类似的问题。 所以我们开始使用两种不同的方法。

✅1️⃣ 使用

sx
道具创建基础组件:

export const BaseSelect = (props: SelectProps) => {
    return (
       <Select
         {...props}
         sx={{
            bgcolor: 'green',
            ...props.sx, //spread your sx from props, so you can override these styles if needed
          }}
         MenuProps={{
            PaperProps: {
               sx: {
                  bgcolor: 'red', //sx for Paper
               },
             },
           }}
         />
      )}


//USAGE
<BaseSelect
     value={age}
     label="Age"
     sx={{
       height: 100, //You can still use sx and override base styling if needed
     }}
   >

✅2️⃣ 创建可重用的

sx
变量:

export const SELECT_BASE_SX: SxProps = {
  bgcolor: 'green',
}

export const PAPER_SX: SxProps = {
  bgcolor: 'red',
}

//USAGE
<Select
  sx={{
    ...SELECT_BASE_SX,
    height: 100,
  }}
  MenuProps={{
    PaperProps: {
      sx: {
        ...PAPER_SX,
      },
    },
  }}
/>

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.