簡體   English   中英

將代碼移動到函數中時,React-leaflet LayersControl 拋出錯誤

[英]React-leaflet LayersControl throws error when moving code into function

抱歉,如果之前在其他地方已經回答過這個問題! 我是 react-leaflet 的新手,並且在這個問題上掙扎了一段時間。

以下代碼無法編譯,並且 chrome 開發人員工具告訴我:此頁面上有 3 個錯誤:
1) "TypeError: addOverlay 不是函數",
2) "TypeError: addOverlay is not a function" 和 ",
3)“類型錯誤:this.props.removeLayer 不是函數”。

我不明白的是:如果我注釋掉“TestOverlay”組件,它就會編譯。 將代碼放入函數中似乎發生了一些魔法,但我不知道問題出在哪里..

使用: "leaflet": "1.7.1", "react": "16.14.0", "react-dom": "16.14.0", "react-leaflet": "2.7.0",

非常感謝您的幫助!

import React from "react";
import { Map, TileLayer, LayersControl, Marker, LayerGroup } from "react-leaflet";

import "./App.css";

function TestOverlay() {
  return <LayersControl.Overlay checked name="Random layer 2">
  <Marker position={[52.339545, 4.900526]} />
</LayersControl.Overlay>;

}

export default function App() {
  return (
    <Map center={[52.339545, 4.900526]} zoom={14}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      <LayersControl position="topright">
        <LayersControl.Overlay checked name="Random layer">
          <Marker position={[52.339545, 4.900526]} />
        </LayersControl.Overlay>
        <TestOverlay/>
      </LayersControl>
    </Map>);
}

來自文檔 1文檔 2

Map:頂級組件實例化一個 Leaflet 地圖並將其提供給它的孩子。

所有組件都是 Leaflet 元素和圖層的 React 包裝器,它們需要一個地圖實例,因此必須包含在頂級組件中。

LayersControl.Overlay 使用 Overlay 類( doc )並且在 Overlay 類中有以下代碼:

 class Overlay extends ControlledLayer {
  constructor(props: ControlledLayerProps) {
    super(props)
    this.contextValue = {
      ...props.leaflet,
      layerContainer: {
        addLayer: this.addLayer.bind(this),
        removeLayer: this.removeLayer.bind(this),
      },
    }
  }

  addLayer = (layer: Layer) => {
    this.layer = layer // Keep layer reference to handle dynamic changes of props
    const { addOverlay, checked, name } = this.props
    addOverlay(layer, name, checked)
  }
}

在構造函數addLayer中分配了一個方法,即this.addLayer this.addLayer addOverlay 內部正在通過 props 進行解構。 最有可能在那時 props 不包含 addOverlay 方法,因此無法檢索,因此發生錯誤。

因此,您無法按照您嘗試的方式使用LayersControl.Overlay 沒有這樣的例子,我認為這是不可能的,因為地圖實例沒有按照應有的方式提供給LayersControl.Overlay

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM