【问题标题】:How can I get the Marker being dragged when event handler is already bound?当事件处理程序已经绑定时,如何让标记被拖动?
【发布时间】:2018-04-19 21:11:54
【问题描述】:

当处理程序是绑定函数时,有没有办法确定正在拖动哪个Marker?这是我的反应组件的 sn-p:

constructor() {
   this.handleMarkerMove = this.handleMarkerMove.bind(this);
}

createMarker() {
   const marker = new google.maps.Marker({...}); 

   google.maps.event.addListener(marker, "dragend", this.handleMarkerMove);
}

handleMarkerMove(e) {
   const latitude = e.latLng.lat();
   const longitude = e.latLng.lng();
   const theMarker = ???

   // this = the class when .bind(this) registered in constructor
}

如果我不使用this.handleMarkerMove = this.handleMarkerMove.bind(this),我将失去对this 的引用,这就是Google 地图发送Marker 的方式。

有没有办法在不创建嵌套函数的情况下将thisMarker 都变为handleMarkerMove(e)

【问题讨论】:

    标签: javascript reactjs google-maps google-maps-markers


    【解决方案1】:

    您不能使用.bind(this),因为this 关键字将引用类本身。最好的选择是使用嵌套函数,这没有什么问题:-)。

    google.maps.event.addListener(marker, 'dragend', (e) => this.handleMarkerMove(e));
    

    您也可以将标记添加为第二个参数:

    const marker = new google.maps.Marker({...}); 
    
    google.maps.event.addListener(marker, 'dragend', this.handleMarkerMove.bind(this, marker));
    

    现在您可以通过事件处理程序中的第二个参数访问标记对象:

    handleMarkerMove(e, marker) {...}
    

    【讨论】:

    • 我希望这是可能的。
    【解决方案2】:

    我相信没有可靠的方法可以做到这一点(除了你所说的),但有一个 repo 可能有助于将 google mapsreact here 集成。

    【讨论】:

      猜你喜欢
      • 2014-11-03
      • 2013-11-02
      • 2018-03-23
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多