首页 > 解决方案 > 使用 geojson pointToLayer 函数时需要正确的方法在 Leaflet 弹出窗口中呈现 jsx 组件

问题描述

嗨,有什么方法可以将 jsx 组件传递给 bindPopup 函数,这样我就可以在单击按钮时推送 redux 命令?

 pointToLayer={(
      geoJsonPoint: Feature<Point, DeviceProperties>,
      latlng,
    ) => {
      const marker = L.marker(latlng);
      marker.setIcon(
        markerIcon({ variant: geoJsonPoint.properties.relation }),
      );

      const sddds = (
        <div className="font-quicksand">
          <h2>{geoJsonPoint.properties.id}</h2>
          <h2>{geoJsonPoint.properties.name}</h2>
          <p>{geoJsonPoint.properties.description}</p>
          <p>{geoJsonPoint.properties.ownerId}</p>
          <a
            onClick={() => {
              dispatch(setDevice(geoJsonPoint.properties));
            }}
          >
            Open device details
          </a>
        </div>
      );

      marker.bindPopup(renderToString(sddds));
      return marker;
    }}

我知道我可以使用反应传单组件,但这样我不能将道具传递给每个标记选项(我的意思是标记作为图层)。

标签: leafletreact-leaflet

解决方案


所以这已经讨论了一点。在讨论这个问题的 react-leaflet repo 中有一个问题,其结论是在bindPopup方法中简单地使用 vanilla JS 来创建您的弹出窗口。我根本不喜欢这个解决方案,尤其是当您尝试从弹出窗口中使用非常面向反应的事件处理程序(如 react-redux 操作)时。

问题React-leaflet geojson onEachFeature popup with custom react component被问到,您可能已经阅读过,因为您renderToString在代码中使用了 react 的方法。但是您可能已经发现,这不会维护您的 JSX 可能包含的任何交互性或 JS。那里的回答者提出了使用模式而不是弹出窗口的想法,但这并不能完全回答您的问题或在基于点层 geojson 的弹出窗口中真正使用 JSX。

最终,您将无法从pointToLayer交互式函数返回 JSX。我认为这将是 react-leaflet 目前没有实现的一个很好的功能。在pointToLayer函数的闭包中,没有直接编写功能齐全的 JSX 的好方法。

我玩了一会儿,试图利用pointToLayer并保存feature每次迭代的状态,然后从中渲染一个MarkerPopup但这让我思考 - 为什么要打扰?只需完全放弃组件并直接从 JSON 对象GeoJSON呈现您Marker的 s 和s 。Popup像这样:

{myGeoJson.features.map((feature, index) => {
  return (
    <Marker
      key={index}
      position={L.latLng(feature.geometry.coordinates.reverse())}
    >
      <Popup>
        <button
          onClick={() => { yourReduxAction() }}
        >
          Click meeee
        </button>
      </Popup>
    </Marker>
  );
})}

工作沙箱

这样,您需要通过手动将 GeoJSON 转换为Markers with来更加努力地工作Popups,但并不像尝试从 JSX ( <GeoJSON />) 到 vanilla JS ( pointToLayer) 再回到 JSX ( <Popup />) 那样向后弯腰。


推荐阅读