如何解决即使使用leaflet.css导入,React传单地图也无法正确显示
我正在尝试使用ionic中的reac-leaflet创建地图,但未正确显示它,也请点击以下链接:Missing Leaflet Map Tiles when using react-leaflet
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='&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上遇到了同样的问题,并且我这样解决了:
在使用传单反应组件的页面(在您的情况下为 Home )中,导入useIonViewDidEnter生命周期方法(see full docs)以了解何时IonPage已完成动画制作,然后触发窗口调整大小事件。
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>
);
}
对我来说很好。 让我知道是否有帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。