1 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
似乎eventHandlers
,雖然它可以作為道具使用MapContainer
(如果你在 vscode fi 上按 ctlr + 空格,它會(huì)彈出)但它在官方API中不可用并且僅適用于的子組件MapContainer。
您想要實(shí)現(xiàn)的目標(biāo)可以useMapEvents
在單獨(dú)的 comp 上使用來(lái)實(shí)現(xiàn),然后作為子項(xiàng)包含在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='© <a >OpenStreetMap</a> contributors'
? ? ? ? url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
? ? ? />
? ? ? <MyComponent />
? ? </MapContainer>
? );
}
另一種方法是在 listen whenReadyprop(沒(méi)有正式記錄,但似乎與whenCreatedprop 類似,但地圖實(shí)例可通過(guò)訪問(wèn)object.target)MapContainer:
<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
<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>
第四種方法是使用whenCreatedprop(官方記錄)MapContainer:
<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);
? ? ? ? });
? ? ? }}
? ? >
...
添加回答
舉報(bào)