javascript - 如何在渲染的 map 中查找与元素关联的数据

我有一个 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>

相似文章

twilio - DevTools 无法加载源 map

我知道Chrome开发工具中有很多关于这些警告的帖子。对于所有这些,解决方案是关闭通知“启用javascript源maps”和“启用CSS源maps”。我想知道的是如何解决这个问题,以及导致这些警告的...

随机推荐

最新文章