大家!我尝试在我的 React 项目中使用 Materialise 风格的 React-leaflet。当我打开模态组件时,我看不到地图。我安装了 npm install react-leaflet,还在index.html [email protected]/dist/leaflet.css 中添加了“ 完整性=“sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=” 跨域=“”/>
import React, { useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
export const MapModal = ({ lnglat }) => {
const mapRef = useRef(null);
useEffect(() => {
// Clean up the map instance when the modal is closed
return () => {
if (mapRef.current) {
mapRef.current.remove();
}
};
}, []);
return (
<div id='MapModal' className='modal'>
<div className='modal-content'>
<MapContainer
center={[48.0196, 66.9237]}
zoom={5}
style={{ height: "50vh", width: "100%" }}
ref={mapRef}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
/>
<Marker position={lnglat}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
</div>
</div>
);
};
MapModal.propTypes = {
lnglat: PropTypes.array,
};
请帮我解决这个问题吗?
将此添加到导入中
import 'leaflet/dist/leaflet.css';
我遇到了同样的问题,这解决了它。
你需要添加一个中间组件来等待引导模态完成初始化,即从你的主组件中添加一个中间组件,在中间组件中你必须设置一个设置的超时时间,例如:
useEffect(() => {
setTimeout(function() {
setShowMap(true);
}, 2000);
}, [isShowMap]);
//In the return:
{
showMap ?
<
CustomMap lat = {
lat
}
lng = {
lng
}
setlat = {
setlat
}
setlng = {
setlng
}
/>:
<
div > < /div>
}