【问题标题】:Custom SVG is not loading in my image tag自定义 SVG 未加载到我的图像标签中
【发布时间】:2021-10-28 09:58:10
【问题描述】:

目前我正在尝试在图像标签内加载我的自定义 svg 组件。但由于某种原因,我无法看到地图组件内的 svg 图像。我的自定义 SVG 文件就是这样,我在 SVG 中加载另一个图像:

<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="85.000000pt" viewBox="0 0 850 1090" preserveAspectRatio="xMidYMid meet">

  <clipPath id="clip">
    <path id="path" transform="translate(0,1090) scale(1,-1)" d="M406 1035 c-32 -49 -201 -104 -323 -105 l-43 0 0 -282 c0 -277 1
    -284 24 -333 39 -82 146 -174 291 -250 l67 -34 61 31 c151 76 265 170 303 253
    23 49 24 57 24 330 l0 281 -103 12 c-124 13 -206 42 -252 87 l-33 34 -16 -24z" />
  </clipPath>

  <image x="-200" y="30" width="1090" height="1090" clip-path="url(#clip)" xlink:href="https://assets.codepen.io/222579/darwin300.jpg" />

  <use xlink:href="#path" fill="none" stroke="gold" stroke-width="30" />
</svg>

而我的图片标签是这样的:

<img src="icon.svg"/>

但是当我去检查网络标签时,它显示的是:

代码沙盒:https://codesandbox.io/s/full-popup-mapbox-stackoverflow-forked-6rupe?file=/src/App.js

【问题讨论】:

    标签: html reactjs svg


    【解决方案1】:

    老实说,我不确定codeandbox 中的外部/跨域图像资源是否存在问题(也可能是本地开发的问题)。标记的duplicate Robert 让我相信问题出在这个特定的 SVG 资产本身。

    不过还是有办法渲染的。

    将 svg 图像导入为 ReactComponent 并渲染它而不是 img 标记。

    Source

    import { ReactComponent as Icon} from "./icon.svg";
    
    ...
    
    <Icon
      style={{
        width: 48,
        height: 48
      }}
      onMouseEnter={() => {
        setSelectedProperty(item);
        setIsPopupShown(true);
      }}
      onMouseOut={() => {
        setSelectedProperty(null);
        setIsPopupShown(false);
      }}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 2019-12-30
      • 2017-07-29
      • 2016-02-25
      • 2021-07-25
      相关资源
      最近更新 更多