问题
Sorry if it this has been answered somewhere else before! I am new to react-leaflet and struggle with this issue for some time now.
The following code does not compile and and the chrome developer tools tell me: 3 errors on this page:
1) "TypeError: addOverlay is not a function",
2) "TypeError: addOverlay is not a function" and ",
3) "TypeError: this.props.removeLayer is not a function".
What I do not understand is: if I comment out the "TestOverlay" component, it compiles. There seems to happen some magic with putting the code into a function, but I have no clue what is the problem..
Using: "leaflet": "1.7.1", "react": "16.14.0", "react-dom": "16.14.0", "react-leaflet": "2.7.0",
Thanks a lot for the help!
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='© <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:
From the documentation1, documentation2
Map: top-level component instantiating a Leaflet map and providing it to its children.
All components are React wrappers for Leaflet elements and layers, they need a map instance and therefore must be included in a top-level component.
LayersControl.Overlay uses Overlay class( doc) and inside Overlay class there is the following code:
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)
}
}
in the constructor addLayer is assigned a method which is this.addLayer.
inside this.addLayer addOverlay is being destructured via props. Most likely at that point props do not contain addOverlay method and therefore cannot be retrieved so the error occurs.
As a result you cannot use LayersControl.Overlay the way you are trying to. There is not such an example and I think it is not possible as the map instance is not provided the way it should to LayersControl.Overlay
来源:https://stackoverflow.com/questions/64934285/react-leaflet-layerscontrol-throws-error-when-moving-code-into-function