0

这是整个代码。

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>

它不起作用。我试图能够通过单击附加到标记数组来向地图添加多个标记,然后映射到数组以一一显示每个标记。

4

1 回答 1

2

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

{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>;
))}

工作代码框

于 2021-04-06T20:45:38.777 回答