我正在尝试将 React-Leaflet 合并到我的 Create React App 中。我可以在底图上叠加 GeoJSON 数据,但我无法在该图层上注册点击。
在调查此问题时,我发现了以下 jsfiddle,https: //jsfiddle.net/n7jmqg1s/6/,它在单击形状时注册事件,如 onEachFeature 函数所示:
onEachFeature(feature, layer) {
console.log(arguments)
const func = (e)=>{console.log("Click")};
layer.on({
click: func
});
}
我尝试将其复制并粘贴到我的反应应用程序中,但它在那里不起作用。我唯一改变的是而不是 window.React/window.LeafletReact 我使用了 es6 导入。我不认为这会导致问题,但我认为这是可能的。
我查看了 onEachFeature 函数的参数。在 jsfiddle 中,我得到了 2 个参数——特征和图层数据的外观。然而,在我复制的示例中,我得到了 3 个参数,其中前两个是空的,第三个参数包含一个包含许多内容的对象,包括 (enqueueCallback : (publicInstance, callback, callerName))
我意识到这有点含糊,但我希望这个问题很容易被识别为对 React 或传单的误解。我认为这与我没有传递正确的范围或直接操作 DOM 或其他事情有关。但我不确定。我将不胜感激任何帮助。
这是我的组件代码:
import React from 'react';
import { Map, TileLayer, Marker, Popup, GeoJSON } from 'react-leaflet';
export default class SimpleExample extends React.Component {
constructor() {
super();
this.state = {
lat: 51.505,
lng: -0.09,
zoom: 8,
};
}
onEachFeature = (feature, layer) => {
layer.on({
click: this.clickToFeature.bind(this)
});
}
clickToFeature = (e) => {
var layer = e.target;
console.log("I clicked on " ,layer.feature.properties.name);
}
render() {
const position = [this.state.lat, this.state.lng];
const geojsonObject = {
'type': 'FeatureCollection',
'crs': {
'type': 'name',
'properties': {
'name': 'EPSG:3857'
}
},
'features': [{
'type': 'Feature',
'geometry': {
'type': 'MultiPolygon',
'coordinates': [
[[[-0.09, 51.505], [-0.09, 51.59], [-0.12, 51.59], [-0.12, 51.505]]],
[[[-0.09, 51.305], [-0.09, 51.39], [-0.12, 51.39], [-0.12, 51.305]]]
]
}
}]
};
return (
<Map center={position} zoom={this.state.zoom} ref='map'>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<GeoJSON
ref="geojson"
data={geojsonObject}
onEachFeature={this.onEachFeature}
/>
</Map>
);
}
}