javascript - React.js 和 Mapbox : mapbox map not rendering properly when using react. js

标签 javascript leaflet reactjs mapbox

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

<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>

但是当我按照以下方式执行时, map 通常根本不会出现,或者即使出现,我也只能在 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 开发人员工具等操作时, map 有时似乎会出现。我不知道发生了什么。当我尝试渲染 map 时,组件是否未正确安装?我认为那是 componentDidMount 应该处理的?我真的很感激任何见解!另外,这张 map 是在一些 Zurb Foundation 元素中渲染的,所以我不知道这是否会有所不同?

最佳答案

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

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

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

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

关于javascript - React.js 和 Mapbox : mapbox map not rendering properly when using react. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930962/

相关文章:

javascript - Vue js 条件布局

javascript - 在 TextArea 中捕捉标签

r - 在 rShiny 应用程序中使用markerClusterOptions() 时弹出传单

leaflet - wkhtmltopdf和传单等待 map

javascript - 鼠标悬停时追加子项

javascript - 二进制转十六进制

javascript - Leaflet Draw revertLayers 不起作用

javascript - 使用 GoLang 后端 React JS Rest API 安全性

javascript - 在 Ant.Design 中个性化 ReactJS 分页样式 - 有什么办法吗?

javascript - Material-UI 嵌套复选框选择不会在 DOM 中呈现对父级的更改