2

我正在关注 Leafletjs 的交互式 choropleth 地图示例,我试图通过使用 GeoJson 对象的 resetStyle 方法和 Map 对象的 fitBounds 方法来添加交互。在传单中,这些方法是通过对各自对象的引用来调用的:

var map = L.map('map');

function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
}

var geojson;
// ... our listeners
geojson = L.geoJson(...);

function resetHighlight(e) {
    geojson.resetStyle(e.target);
}

如何在 react-leaflet 中访问这些方法?从用户交互返回的对象中不存在这些方法。我也尝试从 react-leaflet 导出它们,但这也不起作用。

这是我的jsfiddle

我知道一个月前有人问过同样的问题,但是 access 的解决方案this.refs.geojson.leafletElement.resetStyle(e.target)不再起作用,因为它refs不是.e.targetthise.target

4

2 回答 2

2

一种方法是将“ref”属性附加到 GeoJSON 组件,并通过您的组件传递给您的事件处理程序。

JSFiddle:https ://jsfiddle.net/thbh99nu/2/

    <GeoJson data={statesData} 
                     style={style}
             onEachFeature={onEachFeature.bind(null, this)}
             ref="geojson" />


// reset default style on mouseOut
function resetHighlight (component, e) {
    // Just to show the ref is there during the event, i'm not sure how to specifically use it with your library
    console.log(component.refs.geojson);
  // geojsonresetStyle(e.target);
  // how to encapsulate GeoJson component/object?
}

// `component` is now the first argument, since it's passed through the Function.bind method, we'll need to pass it through here to the relevant handlers
function onEachFeature (component, feature, layer) {
  layer.on({
    mouseover: highlightFeature,
    mouseout: resetHighlight.bind(null, component),
    click: zoomToFeature
  });
}
于 2016-09-22T19:41:10.187 回答
2

您需要向函数发送适当的词法范围,然后您将能够访问 this.refs

例如:

this.highlightFeature.bind(this)

然后它将是

onEachFeature(feature, layer) {
 layer.on({
     mouseover: this.highlightFeature.bind(this),
     mouseout: this.resetHighlight.bind(this),
     click: this.clickToFeature.bind(this)
 });

}

于 2016-09-23T01:46:16.037 回答