d3.js 如何在渲染的Map中查找与元素关联的数据[duplicate]

zbdgwd5y  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(113)

此问题在此处已有答案

How can I pass the index from javascript map function to the onclick function?(5个答案)
6个月前关闭。
我有一个Map,我正在尝试使其具有交互性,以便当用户单击某个特定地区时,它会显示有关该地区的一些数据(x/y/z类别中的人口百分比、人口大小等)。数据集包括所有这些数据以及地理数据。但是,在渲染Map后,我在事件对象中找不到该地区的数据。下面是Map的结构(它位于React组件中):

  1. function Map({ data, selectedDistricts }) {
  2. .
  3. .
  4. .
  5. const districtPathGenerator = d3.geoPath(projection)
  6. function handleClick(e) {
  7. console.log(e) // <-- how to display the data associated with the clicked-on district?
  8. }
  9. return (
  10. <div ref={ref}>
  11. <svg width="500px" height="450px">
  12. <g>
  13. {data.map((district) => {
  14. return (
  15. <path
  16. d={districtPathGenerator(district)}
  17. onClick={(e) => handleClick(e)}
  18. >
  19. </path>
  20. )
  21. })}
  22. </g>
  23. </svg>
  24. </div>
  25. )
  26. }
pbwdgjma

pbwdgjma1#

试试看

  1. function Map({ data, selectedDistricts }) {
  2. .
  3. .
  4. .
  5. const districtPathGenerator = d3.geoPath(projection)
  6. function handleClick(e, district) {
  7. console.log(e, district) // <-- how to display the data associated with the clicked-on district?
  8. }
  9. return (
  10. <div ref={ref}>
  11. <svg width="500px" height="450px">
  12. <g>
  13. {data.map((district) => {
  14. return (
  15. <path
  16. d={districtPathGenerator(district)}
  17. onClick={(e) => handleClick(e, district)}
  18. >
  19. </path>
  20. )
  21. })}
  22. </g>
  23. </svg>
  24. </div>
  25. )
  26. }
展开查看全部
nwlqm0z1

nwlqm0z12#

您也可以在g标记上设置一个事件监听器,并使用event.target来访问被单击的path的细节,这称为事件委派,可以获得很好的性能。
第一个

相关问题