此问题在此处已有答案:
How can I pass the index from javascript map function to the onclick function?(5个答案)
6个月前关闭。
我有一个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>
)
}
2条答案
按热度按时间pbwdgjma1#
试试看
nwlqm0z12#
您也可以在
g
标记上设置一个事件监听器,并使用event.target
来访问被单击的path
的细节,这称为事件委派,可以获得很好的性能。第一个