2016-09-22 49 views
2

我正在关注leafletjs的interactive choropleth map示例,我试图通过使用GeoJson对象的resetStyle方法和Map对象的fitBounds方法来添加交互。React-leaflet:如何调用像resetStyle这样的GeoJson方法?

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); 
} 

我如何可以访问反应小叶的这些方法:在传单,这些方法通过参考相应的对象叫什么?用户交互返回的对象中不存在这些方法。我也尝试从反应传单中导出它们,但这也不起作用。

这是我的jsfiddle

我知道这个同样的问题被要求在一个月前,但解决方案,访问this.refs.geojson.leafletElement.resetStyle(e.target),不会了,因为refs不是e.target属性和this只是指e.target工作。

回答

1

一种方法是将'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 
    }); 
} 
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) 
}); 

}

相关问题