【问题标题】:React-leaflet: How can GeoJson methods like resetStyle be called?React-leaflet:如何调用像 resetStyle 这样的 GeoJson 方法?
【发布时间】:2021-11-28 20:56:31
【问题描述】:

我正在关注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 中访问这些方法?从用户交互返回的对象中不存在这些方法。我也尝试从 react-leaflet 导出它们,但这也不起作用。

这是我的jsfiddle

我知道一个月前有人问过同样的问题,但是访问this.refs.geojson.leafletElement.resetStyle(e.target) 的解决方案不再起作用,因为refs 不是e.target 的属性,this 只是指@987654328 @。

【问题讨论】:

    标签: javascript reactjs leaflet react-leaflet


    【解决方案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)
       });
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 2022-10-14
        • 2021-10-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多