【问题标题】:Rendering a map with a tooltip in React/D3在 React/D3 中使用工具提示渲染地图
【发布时间】:2021-03-06 17:44:57
【问题描述】:

我正在尝试使用 D3 在我的 react-app 中为我的纽约市辖区地图创建一个工具提示。我希望当我将鼠标悬停在区域上时出现工具提示,显示区域编号。现在,我可以让区域编号正确显示,但我无法让工具提示的 div 元素跟随鼠标 - 它停留在屏幕的左上角。有没有办法让 div 元素改变其相对于鼠标位置的位置? (我似乎无法让元素响应不断变化的“left”和“top”样式属性,它们随着鼠标位置的变化而变化。)

import React, { useEffect, useRef } from "react";
import { usePrecinctsMap } from './context/precinctsMapContext'
import * as d3 from "d3";

export const PrecinctsMap = props => {

    const data = usePrecinctsMap()

    const svgRef = useRef()
    const containerRef = useRef()
    const tltpRef = useRef()

    useEffect(() => {
        var tooltip = d3.select(tltpRef.current)
        .attr("class", "tooltip")
        .attr("position", "absolute")
        .style("opacity", 0);

        const svg = d3.select(svgRef.current)
            .attr("height", 500)
            .attr("width", "100%")

        const projection = d3.geoAlbers().fitExtent([[20, 20], [300, 300]], data)

        const pathGenerator = d3.geoPath().projection(projection)

        svg.append("g")
        .selectAll("path")
        .data(data.features)
        .join("path")
        .attr('d', pathGenerator)
        .attr('class', 'precinct')
        .attr('fill', 'transparent')
        .attr('stroke', '#999999')
        .attr('stroke-width', '1')
        .on("mouseover", function(event,d) {
            tooltip.style("left", (event.pageX) + "px")
            .style("top", (event.pageY - 28) + "px");  
        tooltip.transition()
         .duration(200)
         .style("opacity", .9)
         ;
        tooltip.text(d.properties.precinct);
       })
        .on("mouseout", function(d) {
       tooltip.transition()
         .duration(500)
         .style("opacity", 0);
       });
    }, [containerRef.current])

    return (
        
        <div ref={containerRef} style={{ marginBottom: "2rem" }}>
            <div ref={tltpRef}></div>
      <svg ref={svgRef}></svg>
      
    </div>
    )
}

【问题讨论】:

  • 工具提示的 css 是什么样的?
  • 所有的css当前都在代码中——位置:绝对等

标签: javascript html reactjs d3.js


【解决方案1】:

将您的位置样式从绝对更改为固定。

然后在您的 javascript 中,引用 event.clientX + 'px' 和 event.clientY + 'px' 代替 pageY 和 pageX。

【讨论】:

  • 谢谢 - 仍然没有运气。 tooltip div 没有移动,只是停留在角落里。
  • 检查时,工具提示的 left 和 top 值是否改变?我想知道您的事件引用周围的括号是否会导致问题。
  • 工具提示 left 和 top 值确实发生了变化——这让我很困惑。我想知道它是否与反应生命周期和重新渲染有关..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-02
  • 2014-08-28
  • 2022-11-17
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2018-07-02
相关资源
最近更新 更多