我正在构建一个esri项目,我正在跟踪这个演示。我遇到了一个错误,我找不到答案。在演示中,定义了leafletElement,但我的代码中却没有定义它。以下是错误:
无法读取未定义的属性“leafletElement”
以下是代码:
import { StatusBar } from 'expo-status-bar';
import React, { Component, createRef } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import L from 'leaflet';
import * as ELG from 'esri-leaflet-geocoder';
import { Map, MapContainer, TileLayer } from 'react-leaflet';
import leafletMap from 'leaflet-map';
class App extends React.Component {
componentDidMount() {
const map = this.leafletMap.leafletElement;
const searchControl = new ELG.Geosearch().addTo(map);
const results = new L.LayerGroup().addTo(map);
searchControl.on("results", function(data) {
results.clearLayers();
for (let i = data.results.length - 1; i >= 0; i--) {
results.addLayer(L.marker(data.results[i].latlng));
}
});
}
render() {
const center = [37.7833, -122.4167];
return (
<MapContainer
style={{ height: "100vh" }}
center={center}
zoom="10"
ref={m => {
this.leafletMap = m;
}}
>
<TileLayer
attribution="© <a href='https://osm.org/copyright'>OpenStreetMap</a> contributors"
url={"http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"}
/>
<div className="pointer" />
</MapContainer>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default App;发布于 2021-01-21 01:26:28
我使用的是反应传单v-3.0.5
但是:
该示例使用react传单版本2.2.1。

React传单包装器的API在其2和3个主要版本之间发生了很大变化。
https://github.com/PaulLeCam/react-leaflet/blob/master/CHANGELOG.md#v300-2020-10-31
v3是对React传单的完整重写,包含了来自v2的突破性更改。
对于您的情况,最简单的解决方案是降低您的项目中的react传单包的版本,以便更好地与您的示例匹配。
或者阅读新版本的文档并相应地修改代码。在您的例子中,由于您想要一个传单地图实例的句柄,所以您可以使用钩子
function MyComponent() {
const map = useMap()
console.log('map center:', map.getCenter())
return null
}
function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
)
}尽管如此,正如前面提到的,我不确定它是否能像反应一样起作用--本土化的。
https://stackoverflow.com/questions/65813657
复制相似问题