gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:32:22 24 4
gpt4 key购买 nike

上下文

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com