简体   繁体   English

MaterialUI v5 -> 如何设置自动完成选项的样式

[英]MaterialUI v5 -> How to style Autocomplete options

I'm trying to apply some basic styles to the options inside the Autocomplete component from MUI v5.我正在尝试将一些基本的 styles 应用于 MUI v5 的自动完成组件内的选项。 I'm just trying to change the background color on hover, and based on whether or not it is selected.我只是想更改 hover 的背景颜色,并根据它是否被选中。 I've tried 2 approaches based on the documentation, using a theme, and applying the sx prop to Autocomplete.我已经尝试了两种基于文档的方法,使用主题,并将 sx 道具应用于自动完成。

Using Theme almost has me there, code below:使用主题几乎让我在那里,代码如下:

import { createTheme, ThemeProvider } from '@mui/material/styles';

const theme = createTheme({
  components: {
    MuiAutocomplete: {
      styleOverrides: {
        option: {
          '&[aria-selected="true"]': {
            backgroundColor: '#e3abed',
          },

          '&:hover': {
            backgroundColor: '#9c27b0',
          },
          backgroundColor: '#fff',
        },
      },
    },
  },
})

I have the ThemeProvider wrapped around my entire app我将 ThemeProvider 包裹在我的整个应用程序中

and the component:和组件:

<Autocomplete
  options={['1', '2', '3']}
  renderInput={(params) => <TextField {...params} label="Priority" />}
  onChange={(_e, val) => setPriority(val)}
/>

So, this almost works.所以,这几乎可行。 However the [aria-selected="true"] styling is only being applied when I am also hovering over another option in the dropdown.但是 [aria-selected="true"] 样式仅在我也将鼠标悬停在下拉列表中的另一个选项上时才应用。 Otherwise it's the default grey that comes with the component and I don't understand why.否则它是组件自带的默认灰色,我不明白为什么。

The second path I have tried is to use the sx prop on the Autocomplete component.我尝试的第二条路径是在自动完成组件上使用 sx 道具。 In the docs it says you can target child components by their class name: https://mui.com/material-ui/customization/how-to-customize/#overriding-styles-with-class-names在文档中它说您可以通过其 class 名称定位子组件: https://mui.com/material-ui/customization/how-to-customize/#overriding-styles-with-class-names

Here is my component:这是我的组件:

<Autocomplete
  options={['1', '2', '3']}
  renderInput={(params) => <TextField {...params} label="Priority" />}
  onChange={(_e, val) => setPriority(val)}
  sx={{
    '& .MuiAutocomplete-option': {
      backgroundColor: '#000',
    },
    '& .Mui-focused': {
      backgroundColor: 'red',
    },
  }}
  open
/>

That doesn't appear to be having any effect.这似乎没有任何效果。 I've been working on this for almost 2 hours and can't seem to get to the finish line here.我已经为此工作了将近 2 个小时,但似乎无法到达终点线。 Any help would be greatly appreciated.任何帮助将不胜感激。

You can override Autocomplete options css by targeting class您可以通过定位 class 来覆盖自动完成选项 css

'.MuiAutocomplete-popper' '.MuiAutocomplete-popper'

You will have to apply css globally because this node is created outside the root element in DOM.您必须全局应用 css,因为此节点是在 DOM 的根元素之外创建的。

I had the same problem;我有同样的问题; turns out I just needed to explore the Autocomplete API docs' Props section a bit further.原来我只需要进一步探索Autocomplete API 文档的道具部分 There are several customization possibilities if you don't want to deal with global theme customization:如果您不想处理全局主题自定义,则有几种自定义可能性:

  1. The PaperComponent prop allows customization of "[t]he component used to render the body of the popup." PaperComponent允许自定义“用于呈现弹出框主体的组件”。 Note that simply using sx on Autocomplete does not work here because (as @bnays-mhz pointed out) the PopperComponent that the PaperComponent is nested in lives outside the main DOM tree (for z-index/modal UX purposes).请注意,仅在Autocomplete上使用sx在这里不起作用,因为(正如@bnays-mhz 指出的那样) PopperComponent嵌套在主 DOM 树之外的PaperComponent (用于 z-index/modal UX 目的)。
  2. The renderGroup prop allows overriding the rendering of option group headers. renderGroup允许覆盖选项组标题的呈现。
  3. The renderOption prop allows overriding the rendering of individual options. renderOption允许覆盖单个选项的呈现。

This may help you!这可能对你有帮助!

  <Autocomplete
  limitTags={1}
  disablePortal
  id="simple-search"
  value={select.region}
  onChange={handleChange("region")}
  options={region}
  sx={{
  width: { sm: "100%", md: 340 },
  "& + .MuiAutocomplete-popper .MuiAutocomplete-option": {
        backgroundColor: "#363636",
  },
  "& + .MuiAutocomplete-popper .MuiAutocomplete-option[aria-selected='true']":
       {
          backgroundColor: "#4396e6",
       },
  "& + .MuiAutocomplete-popper .MuiAutocomplete-option[aria-selected ='true'] .Mui-focused":
       {
          backgroundColor: "#3878b4",
       },
      }}
                disableCloseOnSelect
                multiple
                renderInput={(params) => (
                  <TextField {...params} label="Region" color="info" />
                )}
              />
function CustomPaper({ children }) {
  return (
    <Paper 
      sx={{
        "& .MuiAutocomplete-listbox": {
          "& .MuiAutocomplete-option[aria-selected='true']": {
            bgcolor: "purple",
            "&.Mui-focused": {
              bgcolor: "purple",
            }
          }
        },
        "& .MuiAutocomplete-listbox .MuiAutocomplete-option.Mui-focused": {
          bgcolor: "red",
        }
      }}
    >
      {children}
    </Paper>
  );
}

Following up on Lars' answer, here's an example using a custom Paper component.继 Lars 的回答之后,这里有一个使用自定义 Paper 组件的示例。 Just pass in the custom Paper component name to the PaperComponent prop on Autocomplete <Autocomplete PaperComponent={CustomPaper} {...blahBlahOtherProps} /> .只需将自定义 Paper 组件名称传递给自动完成<Autocomplete PaperComponent={CustomPaper} {...blahBlahOtherProps} />上的 PaperComponent 道具。 This way is nice if you don't want to override the theme for all Autocomplete components.如果您不想覆盖所有自动完成组件的主题,这种方式很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM