Leaflet.draw React 组件中的样式混乱

Leaflet.draw style messed up in react component

在我的react项目中,我使用leaflet作为地图库。而且我没有使用 react-leaflet 包,而是使用原始的传单库。

现在我想添加leaflet-draw插件,我已经安装了leaflet-draw npm包,我的设置如下:

import 'leaflet-draw'
import './leaflet-draw.less'

class GLMap extends Component {
  componentDidMount () {
    ...
    this.setUpLeafletDraw()
    this.map.on('draw:created', this.leafletDrawHandler)
  }

  leafletDrawHandler = (e) => {
    console.log('11111', e.layer._latlngs)
    const type = e.layerType
    const layer = e.layer

    if (type === 'marker') {
      layer.bindPopup('A popup!')
    }
    this.drawnItemsLayer.addLayer(layer)
  }

  setUpLeafletDraw = () => {
    // this.drawnItems is the layer contains the drawn features
    this.drawnItemsLayer = new L.FeatureGroup()
    this.map.addLayer(this.drawnItemsLayer)
    var drawControl = new L.Control.Draw({
      edit: {
        featureGroup: this.drawnItemsLayer
      }
    })
    this.map.addControl(drawControl)
  }
}

在上面的代码中,this.map是传单Dom实例。至此,传单抽取功能可以正常使用。

但问题是工具栏的样式混乱如下:

那么问题是什么?

很可能 leaflet-draw CSS 文件丢失,其中包含 .leaflet-draw-toolbar 的声明。

它可以像这样从 leaflet-draw导入

import "leaflet-draw/dist/leaflet.draw-src.css";

或通过 public/index.html 从 CDN 引用,如下所示:

<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@latest/dist/leaflet.draw-src.css" />

这里是a demo