[英]Rendering a map with a tooltip in React/D3
我正在嘗試使用 D3 在我的 react-app 中為我的紐約地區地圖創建一個工具提示。 我希望在我將鼠標懸停在一個區域上時出現工具提示,顯示區域編號。 現在,我可以讓區域編號正確顯示,但我無法讓工具提示的 div 元素跟隨鼠標 - 它停留在屏幕的左上角。 有沒有辦法讓 div 元素改變其相對於鼠標位置的位置? (我似乎無法讓元素響應不斷變化的“左”和“頂”樣式屬性,這些屬性隨着鼠標位置的變化而變化。)
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>
)
}
將您的位置樣式從絕對更改為固定。
然后在您的 javascript 中,引用 event.clientX + 'px' 和 event.clientY + 'px' 代替 pageY 和 pageX。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.