javascript - 与多个 React 组件一起使用时,svg 无法正确渲染

标签 javascript css reactjs svg

上下文

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

问题

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

示例

componentA {
 display: none;
}
componentB {
 display: block;
}

SVG does not render correctly

componentA {
 display: block;
}
componentB {
 display: block;
}

SVG renders correctly

我怀疑这可能是我的 svg 的问题,但我不确定,因为我是新来 react 的。下面是 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>

最佳答案

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

我要做的唯一更改是将唯一的 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>

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

关于javascript - 与多个 React 组件一起使用时,svg 无法正确渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603664/

相关文章:

reactjs - react-bootstrap-table-next 中的 noDataText 不起作用

javascript - JSON 未从 Node.js 传递到 .getJSON

javascript - AngularJS:位置更改后刷新 View

javascript - JQuery UI 对话框关闭屏幕

css - WPF ResourceDictionary 和绑定(bind)

javascript - React Router - 从处理程序到 header 的 Prop

javascript - 对 MutationObserver 感到困惑

javascript - 在 EmberJS 中创建完全动态的表

CSS——为什么百分比高度不起作用?

javascript - react redux normalizr : how to deal with nested entities?