与多个反应组件一起使用时,svg 无法正确呈现

Ham*_*med 5 javascript css svg reactjs

语境

我有一个 SVG,它在同一页面上被两个不同的 React 组件(A 和 B)使用。

问题

当组件 A 被分配 'display: none' css 属性时,组件 B 中的 svg 无法正确呈现。

例子

componentA {
 display: none;
}
componentB {
 display: block;
}
Run Code Online (Sandbox Code Playgroud)

SVG 无法正确呈现

componentA {
 display: block;
}
componentB {
 display: block;
}
Run Code Online (Sandbox Code Playgroud)

SVG 正确呈现

我怀疑这可能是我的 svg 的问题,但我不确定,因为我是新手。下面是svg代码。

<svg
  id={id}
  data-name={id}
  xmlns="http://www.w3.org/2000/svg"
  width={width}
  height={height}
  viewBox="0 0 498 305.84">
  <defs>
    <clipPath id="clip-path">
      <path
        fill="none"
        d="M354.47 137.84c1.75-22.18-9.65-52.24-34-73.15-15.94 51.41 30.59 56.14 34 73.15" />
    </clipPath>
    <linearGradient
      id="linear-gradient"
      x1="-146.72"
      y1="416.08"
      x2="-143.8"
      y2="416.08"
      gradientTransform="matrix(7.8 0 0 -7.8 1469.73 3349.9)"
      gradientUnits="userSpaceOnUse">
      <stop offset="0%" stopColor="#62bb46" />
      <stop offset="100%" stopColor="#a2d28a" />
    </linearGradient>
  </defs>
  <g id="Leaf">
    <path
      clipPath="url(#clip-path)"
      fill="url(#linear-gradient)"
      d="M286.058 69.72l66.622-18.076 22.032 81.205-66.622 18.074z" />
    <path
      fill="#62bb46"
      d="M320.48 64.69c23.64 2.71 53.94 33.25 34 73.15 1.76-22.18-9.65-52.24-34-73.15" />
  </g>
</svg>
Run Code Online (Sandbox Code Playgroud)

Sai*_*hna 4

我有一个至少对我有用的简单解决方法。

我要做的唯一更改是将唯一的 id 附加到具有 id 属性的每个元素,

    <svg
      id={id}
      data-name={id}
      ...
      <defs>
        <clipPath id={`clip-path-${id}`}>
          ...
        </clipPath>
        <linearGradient
          id={`linear-gradient-${id}`}
         ...
        </linearGradient>
      </defs>
      <g id={`Leaf-${id}`}>
        <path
          clipPath={`url(#clip-path-${id})`}
          fill={`url(#linear-gradient-${id})`}
          ...
         />
      </g>
    </svg>

Run Code Online (Sandbox Code Playgroud)

通过这样做,始终可以确保 SVG 在不同组件上具有唯一的 id。