我在尝试使用 react-leaflet
的 bounds
属性时遇到了问题。
我的用例是我的应用程序在状态中定义了一些初始边界(比方说,后备边界),并且这些边界在组件的第一次渲染期间传递。应用程序架构要求我发送请求以在组件内设置新边界,问题就来了。
在下面的示例中(我使用 setTimeout
模拟了 AJAX 请求)我们可以注意到超时后来自请求的新边界根本没有设置,我也没有很清楚为什么会这样。
我怀疑是动画的问题,因为当增加超时延迟时,问题没有发生,并且第二个边界设置正确。
我的设置:
"react": "17.0.0"
"leaflet": "1.6.0"
"react-leaflet": "2.7.0"
import React, { useState } from "react";
import { Map, ZoomControl, TileLayer } from "react-leaflet";
import "./styles.css";
import "leaflet/dist/leaflet.css";
export default function App() {
const [bounds, setBounds] = useState([
[75, -25],
[30, 45]
]);
setTimeout(() => {
setBounds([
[59.569068610511465, 10.387057922780514],
[59.565111563593824, 10.397184267640114]
]);
}, 200);
return (
<Map
bounds={bounds}
maxBounds={bounds}
zoomControl={false}
style={{
height: 400,
width: 400
}}
>
<TileLayer
url="//{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}"
maxZoom={21}
minZoom={4}
minZoomIsDrawing={18}
subdomains={["mt0", "mt1", "mt2", "mt3"]}
/>
<ZoomControl />
</Map>
);
}
最佳答案
您需要使用效果来获取 map 实例以更改 map 边界。
检查 here了解更多信息。
const mapRef = useRef(null);
useEffect(() => {
const map = mapRef.current?.leafletElement;
map.fitBounds([
[59.569068610511465, 10.387057922780514],
[59.565111563593824, 10.397184267640114]
]);
}, []);
关于javascript - 动态边界更改不会在 'react-leaflet' 中产生任何影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64714683/