首页 > 解决方案 > 在 React/D3 中使用工具提示渲染地图

问题描述

我正在尝试使用 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>
    )
}

标签: javascripthtmlreactjsd3.js

解决方案


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

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


推荐阅读