简体   繁体   English

如何将工具提示添加到 react + d3 分组和堆叠条形图?

[英]How to add tooltip to a react + d3 grouped and stacked bar chart?

I have a created a stacked and grouped bar chart with react + d3 and i want to add tooltip, i have tried different ways but none of them did work.我创建了一个带有 react + d3 的堆叠和分组条形图,我想添加工具提示,我尝试了不同的方法,但都没有奏效。 the code for tooltip looks like:工具提示的代码如下所示:

 const tooltip = select(svgRef.current) .append("div") .style("position", "absolute") .style("visibility", "visible") .style("background-color", "black") .style("border", "solid") .style("border-width", "1px") .style("border-radius", "5px") .style("padding", "10px") .html("<p>I'm a tooltip written in HTML</p>"); svg .select(".barreact") .on("mouseover", function () { return tooltip.style("visibility", "visible"); }) .on("mousemove", function () { return tooltip .style("top", event.pageY + "px") .style("left", event.pageX + "px"); }) .on("mouseout", function () { return tooltip.style("visibility", "hidden"); });

you can check the full code and demo in demo您可以在演示中查看完整代码和演示

any help to make it work will be appreciated任何帮助使它工作将不胜感激

Use SVG foreignObjects to append HTML to an SVG:使用 SVG foreignObjects将 HTML 附加到 SVG:

const tooltip = select(svg)
  .append("foreignObject")
  .attr("width", 180);

const tooltipDiv = tooltip
  .append("xhtml:div")
  .html("<p>I'm a tooltip written in HTML</p>");

Note that we only set the width.请注意,我们只设置了宽度。 The height is calculated dynamically by looking at the height of the div with the width set : you can also do the opposite, setting an height and introspecting for the width:高度是通过查看宽度设置为 div 的高度来动态计算的:您也可以执行相反的操作,设置高度并内省宽度:

  bars.on("mousemove", function () {
    const htmlContentHeight = tooltipDiv.node().getBoundingClientRect()
      .height;
    tooltip.attr("height", htmlContentHeight);
    tooltip.raise();
    return tooltip
      .attr("x", event.pageX)
      .attr("y", event.pageY - htmlContentHeight);
  })

Since SVG has no z-index, we must put the last element at the top of the SVG, and we can do so with selection.raise .由于 SVG 没有 z-index,我们必须将最后一个元素放在 SVG 的顶部,我们可以使用selection.raise来做到这一点。

CodeSandbox代码沙盒

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

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