我有一張我正在嘗試進行互動的地圖,這樣當用戶單擊特定區域時,它會顯示有關該區域的一些資料(x/y/z 類別中的人口百分比、人口規模等) . 資料集包括所有這些資料以及地理資料。但是,地圖渲染后,我在事件物件中找不到該地區的資料。下面是地圖的結構(它在一個 React 組件中):
function Map({ data, selectedDistricts }) {
.
.
.
const districtPathGenerator = d3.geoPath(projection)
function handleClick(e) {
console.log(e) // <-- how to display the data associated with the clicked-on district?
}
return (
<div ref={ref}>
<svg width="500px" height="450px">
<g>
{data.map((district) => {
return (
<path
d={districtPathGenerator(district)}
onClick={(e) => handleClick(e)}
>
</path>
)
})}
</g>
</svg>
</div>
)
}
uj5u.com熱心網友回復:
嘗試一下
function Map({ data, selectedDistricts }) {
.
.
.
const districtPathGenerator = d3.geoPath(projection)
function handleClick(e, district) {
console.log(e, district) // <-- how to display the data associated with the clicked-on district?
}
return (
<div ref={ref}>
<svg width="500px" height="450px">
<g>
{data.map((district) => {
return (
<path
d={districtPathGenerator(district)}
onClick={(e) => handleClick(e, district)}
>
</path>
)
})}
</g>
</svg>
</div>
)
}
uj5u.com熱心網友回復:
g您還可以在標簽本身上有一個事件偵聽器,并使用event.target來訪問path被點擊的細節。這稱為事件委托,可以帶來出色的性能。
const g = document.querySelector('svg g')
g.addEventListener("click", event => {
console.log(event.target.getAttribute("key"))
})
const data = {
a: "M50 0 L10 10",
b: "M100 10 L20 20",
c: "M200 20 L30 30",
}
g.innerHTML = Object.keys(data).map(key => `
<path
key="${key}"
stroke="black"
stroke-width="5"
d="${data[key]}"
>
</path>
`).join("")
<svg viewBox="0 0 200 200">
<g></g>
</svg>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477305.html
標籤:javascript 反应 svg d3.js 地理
上一篇:無法在Java單元測驗中捕獲值
下一篇:將SVG放置在任何螢屏的底部
