这是整个代码。
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>
它不起作用。我试图能够通过单击附加到标记数组来向地图添加多个标记,然后映射到数组以一一显示每个标记。