简体   繁体   中英

React-leaflet: How can GeoJson methods like resetStyle be called?

I am following leafletjs's interactive choropleth map example and I am trying to add interaction by using the GeoJson object's resetStyle method and the Map object's fitBounds method. In leaflet, these methods are called via a reference to the respective objects:

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

How can I access these methods in react-leaflet? The methods don't exist in the objects returned from user interaction. I also tried exporting them from react-leaflet but that doesn't work either.

Here is my jsfiddle .

I know this same question was asked a month ago, but the solution, to access this.refs.geojson.leafletElement.resetStyle(e.target) , doesn't work anymore because refs is not a property of e.target and this just refers to e.target .

One way would be to attach a 'ref' attribute to the GeoJSON component, and pass through your component to your event handlers.

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

You need to send a proper lexical scope to the functions and then you will be able to access this.refs

for example:

this.highlightFeature.bind(this)

and then it will be

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM