我正在努力使用样式组件而不是材料类来设置我的材料 UI 选择组件的样式。我正在使用 material-ui/core 4.12.3。
如果我使用例如来自材料的旧 makeStyles 组件并创建我自己的类,它就可以正常工作,以及例如内联样式或通过 menuProps 进行样式设置。
作品
const useStyles = makeStyles((theme) => ({
icon: {
top: 0,
marginRight: '1px',
},
selectRoot: {
'&:focus': {
backgroundColor: 'white',
borderRadius: '10px',
},
},
}))
作品
<StyledSelect>
classes={
{
//icon: classes.icon,
//root: classes.selectRoot,
}
}
MenuProps={{
anchorOrigin: {
vertical: 'bottom',
horizontal: 'left',
},
getContentAnchorEl: null,
style: {
maxHeight: 400,
},
}}
style={{
border: '1px solid grey',
backgroundColor: 'white',
borderRadius: '10px',
width: '140px',
height: '40px',
}}
</StyledSelect>
但是对于项目的完整性和限制,我更喜欢使用样式组件来设置样式。
到目前为止,我只设法改变字母颜色。即使我尝试使用开发工具中出现的类名称来设置它的样式,也没有其他方法真正起作用。
不工作(遗憾)
StyledSelect: styled(Select)`
border: '1px solid grey';
backgroundColor: white;
borderRadius: '10px';
width: '140px';
height: '40px'
'&:focus': {
backgroundColor: 'white';
background-color: 'white';
borderRadius: '10px',
};
.MuiSelect-select:focus {
backgroundColor: 'white';
background-color: 'white';
borderRadius: '10px',
},
&.MuiSelect-select:focus {
backgroundColor: 'white',
background-color: 'white',
borderRadius: '10px',
},
& .MuiInputBase-formControl {
border-color: red;
}
icon: {
top: 0,
marginRight: '1px',
},
在这种情况下,材料文档并没有那么有帮助。有任何想法吗 ?
由于 Material UI 组件不是简单的 HTML 元素,因此它并没有做太多事情。例如,如果您在开发工具中查看 HTML 树,“选择”不是呈现为<select>...</select>
而是呈现为...
<div>
<label />
<div>
<div />
<input />
<svg>
<path />
</svg>
<fieldset>
<legend>
<span />
</legend>
</fieldset>
</div>
</div>
样式嵌套在上述组件树的各个级别,因此要修改特定的边框或背景样式,您必须使用特定的选择器准确知道要定位的元素(因为id
每次渲染时属性都会更改)。
相反,您可以继续使用材质文档中提供的 css 属性,但不要尝试通过将 Material UI 根组件定义为样式组件来替换它。如果您将 Material Select 组件包装在您自己的另一个由 styled-components 制作的 div 中,那么您可以将这些属性传递给子 Material 元素,就像您现在所做的那样。
有些属性需要一个“!important”标志来覆盖 Material 中的样式,有些则需要您使用somethingProps
(例如“menuProps”、“inputProps”等)属性来覆盖样式。这是因为虽然使用文档中的类名和“!important”标志手动覆盖它非常适合定位树中的一个(或几个)组件,但当您使用somethingProps
属性时,Material 会自动级联这些树中正确元素的样式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句