![](/img/trans.png)
[英]Javascript event not registering for right click event (in React)
[英]Registering event with react leaflet
我正在尝试将 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
});
}
我尝试将其复制并粘贴到我的 React 应用程序中,但在那里不起作用。 我唯一改变的是使用 es6 导入而不是 window.React/window.LeafletReact。 我不认为这会导致问题,但我认为这是可能的。
我查看了 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>
);
}
}
首先你在渲染函数中定义你的地图:
<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}
对于 ES6,你应该使用这个:
onEachFeature = (feature, layer) => {
layer.on({
click: this.clickToFeature
});
}
取而代之的是:
onEachFeature = (feature, layer) => {
layer.on({
click: this.clickToFeature.bind(this)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.