React-leaflet:如何调用像resetStyle这样的GeoJson方法?

时间:2016-09-22 18:27:38

标签: javascript reactjs leaflet react-leaflet

我正在关注leafletjs的interactive choropleth map示例,我试图通过使用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导出它们,但这也不起作用。

这是我的jsfiddle

我知道一个月前就问了同样的问题,但访问this.refs.geojson.leafletElement.resetStyle(e.target)的解决方案不再有效,因为refs不是e.target和{{this的属性1}}只是引用e.target

2 个答案:

答案 0 :(得分: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
  });
}

答案 1 :(得分: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)
 });

}