React中Material UI小尺寸Button自定义宽度样式失效问题求助
问题解决方法
原因分析
MUI Button的small尺寸变体内置了优先级更高的样式规则(比如min-width或者特定类选择器),导致自定义的width被覆盖,只有height生效。
解决方法
方法1:增强自定义样式的选择器权重
无需使用!important,通过结合MUI内置类名提升选择器优先级:
.MuiButton-root.btn-delete { width: 40px; height: 40px; }
方法2:使用MUI的sx属性直接设置
sx属性的样式优先级高于外部CSS,直接在组件上定义即可:
<Button sx={{ width: 40, height: 40 }} size="small" variant="contained" > <DeleteIcon /> </Button>
方法3:用MUI的styled API封装自定义按钮
适合需要重复使用的场景,直接封装带样式的组件:
import { styled } from '@mui/material/styles'; import Button from '@mui/material/Button'; const CustomDeleteButton = styled(Button)(({ theme }) => ({ width: 40, height: 40, })); // 调用自定义组件 <CustomDeleteButton size="small" variant="contained"> <DeleteIcon /> </CustomDeleteButton>
内容的提问来源于stack exchange,提问作者DangNguyen
相关产品推荐
相关产品推荐

