[英]Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>
I'm using react-leaflet and I added a marker with an event Handler on click to zoom to this marker, but when I try to use const map=useMap() all I get is this error =>:我正在使用 react-leaflet 并在单击时添加了一个带有事件处理程序的标记以缩放到该标记,但是当我尝试使用 const map=useMap() 时,我得到的只是这个错误 =>:
Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>
There might be similar questions but none have answers, can anyone please help with this?可能有类似的问题,但没有答案,有人可以帮忙吗? This is my code:
这是我的代码:
const map = useMap()
return (
<div>
<MapContainer
className="leaflet-container"
center={[33.8735578, 35.86379]}
zoom={9}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
icon={port}
eventHandlers={{
click: (e) => {
map.setView(e.latlng, 14);
},
}}
position={[33.90757548098519, 35.51700873340635]}
></Marker>
</MapContainer>
Thanks!谢谢!
well I solved it by making a separate component for the marker and implement the useMap() in it and it worked as so:好吧,我通过为标记制作一个单独的组件并在其中实现 useMap() 来解决它,它是这样工作的:
import React from "react";
import { Marker, useMap } from "react-leaflet";
export default function Markerwhatever(props) {
const map = useMap();
return (
<div>
<Marker
icon={props.icon}
position={[33.91907336973602, 35.51552625946782]}
eventHandlers={{
click: (e) => {
map.flyTo(e.latlng, 14);
},
}}
></Marker>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.