在 3.x 中的组件中添加 onClick on MapContainer

Add onClick on MapContainer in Component in 3.x

我使用的是以下版本:

"leaflet": "^1.7.1",
"react-leaflet": "^3.0.2",

我想在点击地图时执行一些操作,例如添加标记。

我尝试了 stateless component approach,它似乎有效,但我不太喜欢它,原因有几个。

我尝试使用 eventHandlers 属性:

  render() {
    return <div>
          <MapContainer center={[ 48, 11 ]} zoom={10} scrollWheelZoom={true} eventHandlers={{
            click: () => {
              console.log('map clicked')
            },
          }}>
            <TileLayer .../>
          </MapContainer>
        </div>
  }

但它永远不会触发。

我也读过 MapConsumer 但找不到很好的例子。

如有任何有关在 onClick 事件处理程序中构建的提示,我们将不胜感激。

TIA

似乎 eventHandlers,虽然它在 MapContainer 上作为道具可用(如果你在 vscode f.i 上按 ctlr + space 它会弹出)官方没有API and is intended only for child components of MapContainer, see here and here for Marker.

您想要实现的目标可以使用 useMapEvents 在单独的组件上实现,然后作为 child 在 MapContainer 上包含:

function App() {
  function MyComponent() {
    const map = useMapEvents({
      click: (e) => {
        const { lat, lng } = e.latlng;
        L.marker([lat, lng], { icon }).addTo(map);
      }
    });
    return null;
  }

  return (
    <MapContainer center={[50.5, 30.5]} zoom={13} style={{ height: "100vh" }}>
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <MyComponent />
    </MapContainer>
  );
}

Demo

另一种方法是在 MapContainer 上收听 whenReady prop(没有正式记录,但似乎与 whenCreated prop 类似,但可以通过 object.target 访问地图实例) :

<MapContainer
      center={[50.5, 30.5]}
      zoom={13}
      style={{ height: "100vh" }}
      whenReady={(map) => {
        console.log(map);
        map.target.on("click", function (e) {
          const { lat, lng } = e.latlng;
          L.marker([lat, lng], { icon }).addTo(map.target);
        });
      }}
    >
    ...
</MapContainer>

第三种方法是使用 MapConsumer 作为 MapContainer 的 child (docs):

<MapContainer center={[50.5, 30.5]} zoom={13}>
     <MapConsumer>
            {(map) => {
              console.log("map center:", map.getCenter());
              map.on("click", function (e) {
                const { lat, lng } = e.latlng;
                L.marker([lat, lng], { icon }).addTo(map);
              });
              return null;
            }}
     </MapConsumer>
</MapContainer>

第 4 种方法是在 MapContainer:

上使用 whenCreated 道具(官方记录)
<MapContainer
      center={[50.5, 30.5]}
      zoom={13}
      style={{ height: "100vh" }}
      whenCreated={(map) => {
        map.on("click", function (e) {
          const { lat, lng } = e.latlng;
          L.marker([lat, lng], { icon }).addTo(map.target);
        });
      }}
    >
...