我有一个 map 我正在尝试进行交互,因此当用户单击特定区域时,它会显示有关该区域的一些数据(x/y/z 类别中的人口百分比、人口规模等.)。数据集包括所有这些数据以及地理数据。但是,在渲染 map 之后,我在事件对象中找不到该地区的数据。下面是 map 的结构(它在 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>
)
}
回答1
试试看
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>
)
}
回答2
您还可以在 g
标记本身上设置一个事件侦听器,并使用 event.target
来访问被单击的 path
的详细信息。这称为https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_delegation,可以带来出色的性能。
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>