我正在尝试将 React-Leaflet 合并到我的 Create React App 中。我可以在 basemap 上叠加 GeoJSON 数据,但我无法在该图层上注册点击。
在调查这个问题时,我发现了以下 jsfiddle,https://jsfiddle.net/n7jmqg1s/6/ ,它会在单击形状时注册事件,如 onEachFeature 函数所示:
onEachFeature(feature, layer) {
console.log(arguments)
const func = (e)=>{console.log("Click")};
layer.on({
click: func
});
}
我尝试将其复制并粘贴到我的 React 应用程序中,但它在那里不起作用。我唯一改变的是我使用了 es6 导入而不是 window.React/window.LeafletReact。我不认为这会导致问题,但我想这是可能的。
我查看了 onEachFeature 函数的参数。在 jsfiddle 中,我得到 2 个参数——看起来像是要素和图层数据。但是,在我复制的示例中,我得到 3 个参数,前两个参数为空,第三个参数包含一个包含许多内容的对象,包括 (enqueueCallback : (publicInstance, callback, callerName))
我意识到这有点含糊,但我希望这个问题很容易被识别为对 React 或 leaflet 的误解。我认为这与我没有传递正确的范围或直接操作 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>
);
}
}
最佳答案
首先你在渲染函数中定义你的 map :
<LeafletMap
ref='map'>
<GeoJson
ref="geojson"
data={this.props.data}
onEachFeature={this.onEachFeature.bind(this)}
/>
</LeafletMap>
然后你定义一个 onEachFeature 函数列出所有的监听器
onEachFeature(feature, layer) {
layer.on({
mouseover: this.highlightFeature.bind(this),
mouseout: this.resetHighlight.bind(this),
click: this.clickToFeature.bind(this)
});
}
然后定义每个事件处理函数,例如点击函数 或鼠标悬停
clickToFeature(e) {
var layer = e.target;
console.log("I clicked on " + layer.feature.properties.name);
}
在没有看到 Leaflet 标记代码以及您如何调用 onEachFeature 的情况下,我无法真正帮助您使用 ES6 示例。 您可能不像在 JSFiddle 示例中那样调用它
onEachFeature={this.onEachFeature}
关于javascript - 使用 React 传单注册事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41950931/