【发布时间】:2020-12-14 08:49:37
【问题描述】:
这是我第一次使用 React-Leaflet。我正在做与documentation 中显示的相同的操作,但是在第一次加载页面时地图是灰色的。但是,如果我要调整浏览器的大小,地图会正确呈现并显示地图。
index.js
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""
/>
package.json
"react-leaflet": "^3.0.2",
"leaflet": "^1.7.1",
css 文件
.leaflet-container {
height: 310px;
width: 440px;
margin: 0 auto;
}
我的组件
import React from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
const Location = () => {
return (
<div className="location-container">
<MapContainer
style={{ height: "310px" }}
center={[51.505, -0.09]}
zoom={15}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<Marker position={[51.505, -0.09]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
</div>
);
};
export default Location;
我在我的 index.js 中添加了 leaflet-css,我在我的传单 DOM 中添加了宽度和高度。我注意到第一次加载时,图片不是来自api,但是当我调整浏览器大小时,图片来了。这是一些图片。
首次加载
调整浏览器大小后
【问题讨论】:
-
我找不到将 map.invalidateSize() 添加到我的组件的方法
-
你试过
componentDidMount() { const map = this.mapRef.current.leafletElement; setTimeout(() => { map.invalidateSize(); }, 250); }吗? -
是的,我试过了。但我认为我无法正确设置 mapRef。我使用 useRef 钩子。
const ref = useRef();然后将 ref 添加到<div ref={ref} className="location-container"></div>。useEffect(() => { const map = ref.current.leafletElement; setTimeout(() => {map.invalidateSize(); }, 250); }, []);但它给出了一个错误并说 invalidateSize 不是一个函数 -
好吧,我帮不了你,因为我不是 React 程序员,对不起
标签: javascript reactjs leaflet react-leaflet