React Leaflet - TileLayer 在首次加载时不呈现

React Leaflet - TileLayer does not render when it is first loaded

这是我第一次使用 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='&copy; <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 中添加了传单-css,我在我的传单 DOM 中添加了宽度和高度。我注意到第一次加载时,图片不是来自 api,但是当我调整浏览器大小时,图片出现了。这是一些照片。

首次加载

调整浏览器大小后

我自己想出来了。我写如果有人遇到同样的问题。

我查看了 react-leaflet 的 documentation 并在关于 react-hooks 的部分找到了它。我添加了 useMap 来访问 React-leaflet 中的地图函数。

import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";

然后,我在同一页面上创建了一个新组件。

const ResizeMap = () => {
  const map = useMap();
  map._onResize();
  return null;
};

这里我调用了_onResize方法。因此,当页面首次加载时,它会调整地图位置的大小并正确加载图像。在其他项目中,他们用 map.invalidateSize();

解决了这个问题

我在这里使用了调整大小组件。它必须在 MapContainer 中。

     <MapContainer
        style={{ height: "310px" }}
        center={[51.505, -0.09]}
        zoom={15}
        scrollWheelZoom={false}
      >
        <ResizeMap />
        <TileLayer
          attribution='&copy; <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>