reactjs 使用react-leaflet初始化时,标测图不可见

laik7k3q  于 2023-03-17  发布在  React
关注(0)|答案(3)|浏览(524)

我有一个React组件:

import React, { Fragment } from 'react';
import L from 'leaflet';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';

const customMarker = new L.icon({
    iconUrl: '/images/poemEditorTools/location-pointer-new.svg',
    iconSize: [56, 72],
    iconAnchor: [26, 72],
}); 

const MyPopupMarker = ({ content, position }) => (
    <Marker position={position} icon={customMarker} >
      <Popup>{content}</Popup>
    </Marker>
)

const MyMarkersList = ({ markers }) => {
    const items = markers.map(({ key, ...props }) => (
        <MyPopupMarker key={key} {...props} />
    ))
    return <Fragment>{items}</Fragment>
}

const markers = [
    { key: 'marker1', position: [51.5, -0.1], content: 'My first popup' },
    { key: 'marker2', position: [51.51, -0.1], content: 'My second popup' },
    { key: 'marker3', position: [51.49, -0.05], content: 'My third popup' },
]

class MapWithPoems extends BaseComponent {
    render() {
        return (
            <Map center={[51.505, -0.09]} zoom={13} style={{ height: "500px", width: "100%" }} >
                <TileLayer
                    url={
                        "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}"
                    }
                />
                <MyMarkersList markers={markers} />
            </Map>
        );
    }
}

export default MapWithPoems;

问题是当页面被下载的时候,Map被收缩到容器的左边。我必须调整窗口的大小,使Map以全宽显示。见图片。

这里有什么问题?:)

mf98qq94

mf98qq941#

在初始化Map后,必须调用map.invalidateSize();
也许这个链接可以帮助你在reactjs中使用它:https://stackoverflow.com/a/56184369/8283938

iih3973s

iih3973s2#

使用react钩子。这个成功了:

const map = useMap()

useEffect(() => {
    setTimeout(() => { 
        map.invalidateSize(); 
    }, 250); 
}, [map])

但是这个解决方案对我来说有点老套,250ms似乎是任意的。

lmvvr0a8

lmvvr0a83#

使用react钩子,不使用setTimeout()。这个实现对我很有效。

const setMap = ( map: LeafletMap ) => {
        const resizeObserver = new ResizeObserver( () => {
                map.invalidateSize()
        })
        const container = document.getElementById('map-container')
        resizeObserver.observe(container!)
}

<MapContainer
...other properties
id='map-container'
whenCreated={setMap}

>

</MapContainer>

whenCreated允许您使用Map示例作为函数的参数,请检查此react-leafter documentation
我从Michael MacFadden's StackOverflow answer中获得了使用ResizeObersver的想法

相关问题