当事件处理程序已经绑定时,如何让标记被拖动?

How can I get the Marker being dragged when event handler is already bound?

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

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)

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

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

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) {...}