处理 google.maps.infoWindow 内的按钮事件 - ReactJS

Handle button events inside of google.maps.infoWindow - ReactJS

我正在尝试处理 google.maps.infoWindow 中按钮的点击事件。我试图通过 infoWindow 内容将函数名称传递给 onClick 但没有成功。所以,我搬到 getElementById 但也没有 success.The return of getElementById("polyButton") is null (Cannot read 属性 'addEventListener' of null ).

代码:


 fpolylineHandler(event) {
    console.log("handler", event);
  }

 infoPolyline(Polyline, map, maps, event) {
    var infowindow = new maps.InfoWindow({
      content: " ",
    });

    
    infowindow.setContent(
      "<div style='color: black'>" +
        "<p>Event Name: " +
        "</p>" +
        "<p>Event Type: " +
        "</p>" +
        "<p>Cause: " +
        "</p>" +
        "<p>Date: " +
        "</p>" +
        "<p>Time: " +
        "</p>" +
        "<button id='polyButton'>Click me</button>" +
        "</div>"
    );

    var btn = document.getElementById("polyButton");
    btn.addEventListener("click", this.fpolylineHandler.bind(this));

    infowindow.setPosition(event.latLng);
    infowindow.open(map, Polyline);
  }

作为参考,我试过这样使用 onClick

...
 infowindow.setContent(
      "<div style='color: black'>" +
        "<p>Event Name: " +
        "</p>" +
        "<p>Event Type: " +
        "</p>" +
        "<p>Cause: " +
        "</p>" +
        "<p>Date: " +
        "</p>" +
        "<p>Time: " +
        "</p>" +
        "<button id='polyButton'onClick='this.fpolylineHandler'>Click me</button>" +
        "</div>"
    );

...

有趣的是当使用 onClick='this.fpolylineHandler()' 时出现了一个错误,说这不是一个函数。在上面的例子中,什么都不做。

即使在 dom 上安装后读取,该元素在地图上尚不存在。所以,为了解决这个问题,我们需要添加一个 dom 监听器:

 maps.event.addListener(infowindow, "domready", function () {

      document.getElementById("polyButton").onclick=fpolylineHandler
  
    });