tra*_*ton 5 reactjs material-ui
我正在尝试将一些基本样式应用于 MUI v5 中的自动完成组件内的选项。我只是想根据是否选择它来更改悬停时的背景颜色。我尝试了两种基于文档的方法,使用主题,并将 sx 属性应用于自动完成。
使用主题几乎让我在那里,代码如下:
import { createTheme, ThemeProvider } from '@mui/material/styles';
const theme = createTheme({
components: {
MuiAutocomplete: {
styleOverrides: {
option: {
'&[aria-selected="true"]': {
backgroundColor: '#e3abed',
},
'&:hover': {
backgroundColor: '#9c27b0',
},
backgroundColor: '#fff',
},
},
},
},
})
Run Code Online (Sandbox Code Playgroud)
我将 ThemeProvider 包裹在我的整个应用程序中
和组件:
<Autocomplete
options={['1', '2', '3']}
renderInput={(params) => <TextField {...params} label="Priority" />}
onChange={(_e, val) => setPriority(val)}
/>
Run Code Online (Sandbox Code Playgroud)
所以,这几乎有效。然而,只有当我将鼠标悬停在下拉列表中的另一个选项上时,才会应用 [aria-selected="true"] 样式。否则它是组件附带的默认灰色,我不明白为什么。
我尝试的第二条路径是在自动完成组件上使用 sx 属性。在文档中,它表示您可以通过类名称来定位子组件:https://mui.com/material-ui/customization/how-to-customize/#overriding-styles-with-class-names
这是我的组件:
<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
/>
Run Code Online (Sandbox Code Playgroud)
这似乎没有任何效果。我已经为此工作了近两个小时,但似乎无法到达终点线。任何帮助将不胜感激。
小智 5
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>
);
}
Run Code Online (Sandbox Code Playgroud)
继 Lars 的回答之后,这里有一个使用自定义 Paper 组件的示例。只需将自定义 Paper 组件名称传递给 Autocomplete 上的 PaperComponent 属性即可<Autocomplete PaperComponent={CustomPaper} {...blahBlahOtherProps} />。如果您不想覆盖所有自动完成组件的主题,那么这种方法很好。
您可以通过目标类覆盖自动完成选项 css
'.MuiAutocomplete-popper'
您必须全局应用 css,因为该节点是在 DOM 中的根元素外部创建的。