使用材料ui svg图标作为背景图像

我可以使用@material-ui/icons svg图像作为其他元素的背景吗?尝试了下面的代码,但是没有用。

import CarIcon from '@material-ui/icons/DriveetaRounded';

const carIcon = <CarIcon />

function Cover(){
  return (
    <div
        classname={classes.cover}
        style={{ backgroundImage: 'url('+ carIcon+')' }}
    />
  )
}
iCMS 回答:使用材料ui svg图标作为背景图像

@material-ui/icons是React组件,如果您打开它们的源代码,它们仅包含使用实用程序功能封装在<svg>标记中的SVG数据。但是,您可以通过直接使用背景图片和一些样式来模拟背景图片的行为:

import CarIcon from '@material-ui/icons/DriveEtaRounded';

function Cover(){
  return (
    <div style={{position: 'relative',width: '200px',height: '100px'}}>
      <CarIcon style={{position: 'absolute',left: 0,top: 0,width: '100%',height: '100%'}} />
    </div>
  )
}

这是一个示例,但是只要父元素的尺寸由其他内容设置,它就可以使用。您还可以通过将background-size: cover添加到图标组件来模拟preserveAspectRatio='xMidYMid slice'的行为(默认值对应于contain)。 这种方法的另一个好处是图标仍然是SVG,可以进一步设置样式或动画。

本文链接:https://www.f2er.com/2275276.html

大家都在问