简体   繁体   English

如何使用 d3 动态为 svg 中的路径元素添加颜色并做出反应

[英]How to add color to a path element in an svg dynamically with d3 and react

I have an SVG icon:我有一个 SVG 图标:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
  <circle cx="12" cy="12" r="12" />
  <path class="svg-fill"
    d="M12,2A10,10,0,1,0,22,12,10,10,0,0,0,12,2Zm1,3.3,1.35-1a8,8,0,0,1,4.38,3.34L18.34,9,17,9.49,13,6.7Zm-3.35-1L11,5.3V6.7L7,9.49,5.66,9,5.27,7.69A8.1,8.1,0,0,1,9.65,4.35ZM7.08,17.11l-1.14.1A7.94,7.94,0,0,1,4,12c0-.12,0-.23,0-.35l1-.73,1.38.48,1.46,4.34Zm7.42,2.48a7.83,7.83,0,0,1-5,0L8.81,18.1,9.45,17h5.11l.64,1.11ZM14.27,15H9.73L8.38,11,12,8.44,15.63,11Zm3.79,2.21-1.14-.1-.79-1.37,1.46-4.34L19,10.93l1,.73c0,.11,0,.22,0,.34A7.94,7.94,0,0,1,18.06,17.21Z" />
</svg>

Which I'm trying to render on a D3 graph by using:我正在尝试使用以下方法在 D3 图表上呈现:

  svg
    .append('image')
    .attr('xlink:href', MyIcon)

How can I change the color of the path in the svg dynamically, as I will be running the append code from a function something like:如何动态更改 svg 中路径的颜色,因为我将从 function 运行 append 代码,例如:

const renderIcon = (iconColor) => {
  svg
    .append('image')
    .attr('xlink:href', MyIcon)
    // code to apply color param to the icon path

}

Couldn't find a nice way of actually getting the above working.找不到真正让上述工作的好方法。 The solution that I ended up finding was to instead define my icons in an defs element within an svg element in the return statement of my component:我最终找到的解决方案是在我的组件的 return 语句中的 svg 元素内的 defs 元素中定义我的图标:

return (
<svg>
  <defs>
    <MyIcon color={myColor1} id="myIcon1" />
    <MyIcon color={myColor2} id="myIcon2" />
  </defs>
</svg>
)

Where MyIcon would look something like: MyIcon 看起来像这样的地方:

<g fill={color} id={id}>
  // other svg elements
</g>

And then use them by appending a use element to the svg element and passing in the icons id attribute:然后通过将use元素附加到svg元素并传入图标id属性来使用它们:

svg.append('use').attr('href', '#myIcon1');
svg.append('use').attr('href', '#myIcon2');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM