即使使用 leaflet.css 导入,React 传单地图也无法正确显示

React leaflet map not correctly displayed even with leaflet.css import

我正在尝试使用 ionic 中的 reac-leaflet 创建地图,但我没有正确显示它,同样遵循此 link:

WINDOW 调整大小修复它。我在第一次登录时做错了什么?

第一次访问时,这是地图:

调整大小后:

这里是代码。

在index.html

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"/>

Home.tsx简化。

import { Map, Marker, Popup, TileLayer } from 'react-leaflet';

function Home() {

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar color="primary">
          <IonTitle>Logged in ... </IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        <Map center={[45.24,8.55]} zoom={13}>
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[45.24,8.55]}>
          <Popup>
            A pretty CSS3 popup. <br /> Easily customizable.
          </Popup>
        </Marker>
        </Map>
      </IonContent>
    </IonPage>
  )
}

export default Home; 

在 css 文件中。

.leaflet-container {
  height: 100%;
  width: 100%;
} 

谢谢。

这是我目前所做的并且对我有用:

windowDimensions.tsx

import { useState, useEffect } from 'react';

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height,
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions(),
  );

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowDimensions;
}

app.js 或 componentfile.js

import useWindowDimensions from 'path/to/useWindowDimensions'; //in my case i saved it as app/utils/windowDimensions
    <Map style={{height: mapHeight}} />

注意:app.js 仅包含与修复相关的代码

  <link href='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.css' rel='stylesheet'>

试试这个

我在 Ionic 5 和 React Leaflet 3 上遇到了同样的问题,我是这样解决的:

在你使用leaflet-react组件的页面中(在你的例子中Home),导入useIonViewDidEnter生命周期方法(see full docs) 知道 IonPage 何时完成动画,然后触发 window-resize 事件。

import { IonPage, useIonViewDidEnter, ... } from '@ionic/react';
function Home() {

     /* 
      * trigger a 'window-resize' event when Page has finished, 
      * rendering and animating, so leaflet map can read a 
      * consistent height value
      */
     useIonViewDidEnter(() => {
        window.dispatchEvent(new Event('resize'));
     });

     return (
        <IonPage>
           ... your Leaflet component...
        </IonPage>
     );
}

对我来说效果很好。 如果有帮助,请告诉我。