如何不使用sx属性修改MUI SvgIcon自定义SVG的描边颜色?
关于Material UI SvgIcon设置描边色的问题
我目前可以通过<SvgIcon>组件的color属性成功修改自定义SVG的填充颜色,代码示例如下:
import { ReactComponent as MyIcon } from '../my_custom_logo.svg'; <SvgIcon component={MyIcon} inheritViewBox color="primary" />
现在想修改描边颜色,能不能通过<SvgIcon>的其他内置属性实现,而非使用sx={{ stroke: theme.palette.primary.main }}?(以下是用sx实现的可行版本)
import { ReactComponent as MyIcon } from '../my_custom_logo.svg'; <SvgIcon component={MyIcon} inheritViewBox color="primary" sx={{ stroke: theme.palette.primary.main }} />
解答:
Material UI的<SvgIcon>组件本身没有专门用于设置描边色的内置属性,默认的color属性仅会作用于SVG的fill样式,无法直接控制stroke。不过可以通过以下两种方式避免重复编写sx属性:
修改自定义SVG源码,复用
color属性
打开你的my_custom_logo.svg文件,将所有需要设置描边的元素的stroke属性改为currentColor。这样SVG的描边色会继承<SvgIcon>的color属性值,无需额外配置:<!-- 修改后的SVG示例 --> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path d="M12..." fill="currentColor" stroke="currentColor" stroke-width="2"/> </svg>使用时直接沿用原来的代码即可,填充和描边都会同步
color指定的颜色:import { ReactComponent as MyIcon } from '../my_custom_logo.svg'; <SvgIcon component={MyIcon} inheritViewBox color="primary" />封装Styled组件预设描边样式
用Material UI的styled工具封装一个带预设描边色的图标组件,后续使用时直接调用即可:import { styled } from '@mui/material/styles'; import { SvgIcon } from '@mui/material'; import { ReactComponent as MyIcon } from '../my_custom_logo.svg'; const StyledMyIcon = styled(SvgIcon)(({ theme }) => ({ stroke: theme.palette.primary.main, })); // 使用示例 <StyledMyIcon component={MyIcon} inheritViewBox color="primary" />
如果需要灵活切换不同的描边色,也可以给Styled组件添加自定义props来动态传递颜色值。
内容的提问来源于stack exchange,提问作者Stefan Walter
相关产品推荐
相关产品推荐

