ReactJS with Leaflet: tiles not correctly displaye

2019-09-06 19:28发布

问题:

I am building an application using Semantic UI and ReactJS. I am using a tab module to contain my map, which uses the Leaflet Javascript library to render the map.

The problem is that the tiles do not display correctly until the page is resized.

The is what I have tried:

MapComponent = React.createClass({
  componentDidMount() {
    let map = L.map('map')
    L.tileLayer.provider('Thunderforest.Outdoors').addTo(map)
    map.setView([lat, long], zoom)
    map.invalidateSize(false)
  }
}

Which did not seem to fix the problem.

I tried setting a timeout, like so:

MapComponent = React.createClass({
  componentDidMount() {
    let map = L.map('map')
    L.tileLayer.provider('Thunderforest.Outdoors').addTo(map)
    Meteor.setTimeout(() => {
      map.invalidateSize(false)
    }, 2000)
    map.setView([lat, long], zoom)
  }
})

Which sometimes worked by setting the timer to 2000, but sometimes it needed to be set to 5000, which is a bit crazy in my opinion.

From what I have read, calling the invalidateSize() function should fix the problem. Any help solving this problem would be greatly appreciated. Thank you.

回答1:

Call invalidateSize once the tab containing your map becomes visible. In Semantic UI's tab module you can do that by using the onVisible callback:

Called after a tab becomes visible

http://semantic-ui.com/modules/tab.html#/settings

<div class="ui menu top">
    <a class="item" data-tab="map">Map</a>
</div>

$('.top.menu .item').tab({
    'onVisible': function () {
        // Do stuff
    }
});