试图在点击 React Leaflet 地图的地方显示标记

Trying to display a marker where clicked on React Leaflet map

这是完整的代码。

import React, { useState } from "react";
import { Marker, Popup, useMapEvents } from "react-leaflet";

const AddMarkers = () => {
  const [markers, setMarkers] = useState([
    {
      lat: 40,
      lng: -95.6268544,
    },
  ]);

  const map = useMapEvents({
    click: (e) => {
      setMarkers([...markers, e.latlng]);
    },
  });
  return (
    <>
      {/* {markers.map((marker, i) => {
        <Marker key={`marker-${i}`} position={marker}>
          <Popup>
            <span>
              A pretty CSS3 popup. <br /> Easily customizable.
            </span>
          </Popup>
        </Marker>;
      })} */}
      <Marker position={markers[0]}>
        <Popup>
          <span>
            A pretty CSS3 popup. <br /> Easily customizable.
          </span>
        </Popup>
      </Marker>
    </>
  );
};

export default AddMarkers;

当前的 ACTIVE(看看被注释掉的部分)代码段仅用于显示一个标记。但是当你取消注释这部分时

      {/* {markers.map((marker, i) => {
        <Marker key={`marker-${i}`} position={marker}>
          <Popup>
            <span>
              A pretty CSS3 popup. <br /> Easily customizable.
            </span>
          </Popup>
        </Marker>;
      })} */}

并注释掉这部分。

      <Marker position={markers[0]}>
        <Popup>
          <span>
            A pretty CSS3 popup. <br /> Easily customizable.
          </span>
        </Popup>
      </Marker>

没用。我试图通过单击附加到标记数组来向地图添加多个标记,然后在数组上映射以逐个显示每个标记。

如果这是您的确切代码,这是一个简单的语法错误:

{markers.map((marker, i) => { // <----- curly brace bad
  <Marker key={`marker-${i}`} position={marker}>
    <Popup>
      <span>
        A pretty CSS3 popup. <br /> Easily customizable.
      </span>
    </Popup>
  </Marker>;
})}

您不会返回 map 语句中的任何内容。应该是

{markers.map((marker, i) => (  // <---- parantheses good
  <Marker key={`marker-${i}`} position={marker}>
    <Popup>
      <span>
        A pretty CSS3 popup. <br /> Easily customizable.
      </span>
    </Popup>
  </Marker>;
))}

Working codesandbox