我需要自定义 material-ui 自动完成控件,所以它不是那么高。我发现一个示例可以很好地使用自动完成文本字段上的 createMuiTheme 更改 MuiOutlinedInput 轮廓颜色。代码和盒子在这里:Code Example
这是我的主题覆盖代码,我为输入类的填充添加了一个覆盖:
const theme = createMuiTheme({
overrides: {
MuiOutlinedInput: {
root: {
"& $notchedOutline": {
borderColor: "green"
},
"&:hover $notchedOutline": {
borderColor: "red"
},
"&$focused $notchedOutline": {
borderColor: "purple"
},
"& $input": {
padding: "1px"
}
}
}
}
});
这是组件代码:
<Autocomplete
id="country-select-demo"
style={{ width: 300 }}
options={countries}
getOptionLabel={option => option.label}
renderInput={params => (
<MuiThemeProvider theme={theme}>
<TextField {...params} label={"Countries"} variant="outlined" />
</MuiThemeProvider>
)}
/>
问题是我对输入类的填充被这个覆盖了:
.MuiAutocomplete-inputRoot[class*="MuiOutlinedInput-root"] .MuiAutocomplete-input
我可以做些什么来使我的自定义不被上述覆盖?除了 createMuiTheme 之外,我还对其他技术持开放态度,或者对自动完成的其他部分进行样式设置。我只需要让它不那么高。
谢谢!
最佳答案
这是获得合适的CSS specificity的问题为您的覆盖。增加特异性的一种简单方法是重复上课。
在下面的例子中,我使用 &&& $input
这相当于拥有 .MuiOutlinedInput-root.MuiOutlinedInput-root.MuiOutlinedInput-root .MuiOutlinedInput-input
:
const theme = createTheme({
overrides: {
MuiInputLabel: {
outlined: {
transform: "translate(14px, 12.5px) scale(1)"
}
},
MuiOutlinedInput: {
root: {
"& $notchedOutline": {
borderColor: "green"
},
"&:hover $notchedOutline": {
borderColor: "red"
},
"&$focused $notchedOutline": {
borderColor: "purple"
},
"&&& $input": {
padding: "1px"
}
}
}
}
});
另一个有点难看的选项,但更明显的是您要覆盖的默认样式如下:
const theme = createTheme({
overrides: {
MuiInputLabel: {
outlined: {
".MuiAutocomplete-root &:not(.MuiInputLabel-shrink)": {
transform: "translate(14px, 12.5px) scale(1)"
}
}
},
MuiOutlinedInput: {
root: {
"& $notchedOutline": {
borderColor: "green"
},
"&:hover $notchedOutline": {
borderColor: "red"
},
"&$focused $notchedOutline": {
borderColor: "purple"
}
}
},
MuiAutocomplete: {
inputRoot: {
'&&[class*="MuiOutlinedInput-root"] $input': {
padding: 1
}
}
}
}
});
请注意,您仍然需要将
&
加倍。为了获得胜过默认样式的特异性。此版本特定于自动完成,而不是影响所有概述的输入。如果您不想将此覆盖应用于主题中的整个应用程序,您可以使用
withStyles
自定义自动完成组件。像下面这样:import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { withStyles } from "@material-ui/core/styles";
const NoPaddingAutocomplete = withStyles({
inputRoot: {
'&&[class*="MuiOutlinedInput-root"] $input': {
padding: 1
},
"& .MuiOutlinedInput-notchedOutline": {
borderColor: "green"
},
"&:hover .MuiOutlinedInput-notchedOutline": {
borderColor: "red"
},
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: "purple"
}
},
input: {}
})(Autocomplete);
export default function CountrySelect() {
return (
<NoPaddingAutocomplete
id="country-select-demo"
style={{ width: 300 }}
options={countries}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField {...params} label={"Countries"} variant="outlined" />
)}
/>
);
}
相关回答:
相关文档:
&
关于reactjs - 如何在 Material-UI 自动完成控件中自定义填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60531601/