在 React 中调整样式化组件容器大小时,Mapbox GL JS 控件脱离地图

Mapbox GL JS Controls Go Off the Map when Resizing a styled-components Container in React

我在 React 中有一个基本的 Mapbox GL 地图组件,其容器使用样式化组件进行样式化。应用程序中有一个操作会导致地图容器根据用户输入调整大小。

但是,当地图调整大小时,比例控件和导航控件都不再位于地图容器内。我可以通过固定导航控件在 css 中的位置来解决这个问题,但它对比例尺没有帮助。

这些元素飞离地图容器是否有原因?这是代码片段和样式化的组件:

import React, { Component } from 'react'
import mapboxgl from 'mapbox-gl'
import styled from 'styled-components'

import { MapContainer } from './styled'

const MapContainer = styled('section')`
  width: 100vw;
  height: ${props => props.height};
`

class Map extends Component {
  constructor(props) {
    super(props)
    const { lat, lng, zoom } = this.props

    this.state = {
      lng,
      lat,
      zoom
    }
  }

  componentDidMount() {
    const { accessToken } = this.props
    const { lng, lat, zoom } = this.state

    mapboxgl.accessToken = accessToken
    this.map = new mapboxgl.Map({
      container: this.mapContainer,
      style: 'mapbox://styles/mapbox/satellite-streets-v9',
      center: [lng, lat],
      zoom
    })

    const scale = new mapboxgl.ScaleControl({
      maxWidth: 80,
      unit: 'metric'
    })

    this.map.addControl(scale)

    this.map.addControl(
      new mapboxgl.NavigationControl({ showCompass: false }),
      'top-left',
    )

    this.map.once('load', () => {
      this.map.resize()
    })
  }

  componentDidUpdate(prevProps) {
    const { height } = this.props

    if (prevProps.height !== height) {
      this.map.resize()
    }
  }


  render() {
    const { height } = this.props

    return (
        <MapContainer
          height={height}
          ref={el => {
            (this.mapContainer = el)
          }}
        />
    )
  }
}


export default Map

发生这种情况是因为当地图容器调整大小时,styled-components 会生成新的 class 名称。新的 class 名称将不再包含最初在调用 new mapboxgl.Map() 时添加的 mapboxgl-map class。

尝试将 mapboxgl-map 作为 className 属性 添加到 <MapContainer> 组件以确保维护 class 名称:

<MapContainer
      className='mapboxgl-map'
      height={height}
      ref={el => {
        (this.mapContainer = el)
      }}
    />

感谢 Brendan McGill 解决了这个问题并在此处提供了更多详细信息:https://github.com/mapbox/mapbox-gl-js/issues/6946