React.js 和 Mapbox:使用 react.js 时地图框地图无法正确渲染

React.js and Mapbox: mapbox map not rendering properly when using react.js

本文关键字:js 地图 Mapbox 使用 react React      更新时间:2023-09-26

我正在学习同时使用 react 和 mapbox,但我正在努力解决为什么我的 mapbox map 在通过 React 加载时无法正确渲染。 当我正常加载它(没有 React.js)时,没有问题,因为以下代码有效并且地图正常显示:

<script src="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css"/>
<div> id="map"></div>
    <script>                
    var map = L.mapbox.map('map', 'blabla.blabla').setView([lat, long], 9);
    </script>

但是当我按照以下方式进行操作时,地图通常根本不会出现,或者当它出现时,我只在div 的左上角看到它的一部分。

<script src="path/to/react.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/v2.1.5/mapbox.css"/>
<div id="react-content">
    <script src="path/to/react/content.js'></script>
</div>
//now inside react/content.js, there is a mapbox component inside an outer component. I'm leaving out the rest of the code to save space, and I believe that I am rendering the OuterComponent and the MapBoxMap component correctly inside that.
var MapBoxMap = React.createClass({
    componentDidMount: function() {
        L.mapbox.accessToken = this.props.accessToken;
        var map = L.mapbox.map(this.getDOMNode(), this.props.mapId)
            .setView([15, -105], 9);            
    },
    render: function() {
        return (
                <div id="map"></div>
        );
    }
});

执行缩放或打开 chrome 开发人员工具等操作似乎有时会显示地图。 我不知道发生了什么。 当我尝试渲染地图时,组件是否未正确挂载? 我以为这就是DidMount应该照顾的组件? 我真的很感激任何见解! Alos,这张地图正在一些 Zurb 基金会元素中渲染,所以我不知道这是否有区别?

你缺少相关的 CSS?您始终需要设置元素的高度:

html, body, #map {
    height: 100%;
}

由于 React 的原因,我无法进行测试,但听起来地图无法从元素中获得正确的尺寸。如果您没有设置正确的 CSS 或元素有display: none;,通常会发生这种情况 如果设置正确的 CSS 不起作用,您可以尝试使大小无效,以便地图自行重置。 L.mapbox.Map有一个可以调用的invalidateSize方法,请参阅:

http://leafletjs.com/reference.html#map-invalidatesize