简体   繁体   English

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

[英]Handle button events inside of google.maps.infoWindow - ReactJS

I'm trying to handle the click event of a button inside a google.maps.infoWindow.我正在尝试处理 google.maps.infoWindow 中按钮的单击事件。 I tried to pass the function name to onClick via infoWindow contents but didn't work.我试图通过 infoWindow 内容将 function 名称传递给 onClick 但没有奏效。 So, I moved to getElementById but also without success.The return of getElementById("polyButton") is null (Cannot read property 'addEventListener' of null ).所以,我转移到getElementById但也没有成功。 getElementById("polyButton")的返回是 null (无法读取 null 的属性 'addEventListener' )。

The code:编码:


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

for reference, I tried to use onClick like this:作为参考,我尝试像这样使用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>"
    );

...

The interesting part was when using onClick='this.fpolylineHandler()' appeared an error saying that was not a function.有趣的部分是当使用onClick='this.fpolylineHandler()'时出现一个错误,说这不是 function。 On the example above, simply does nothing.在上面的例子中,什么都不做。

Even reading after mounted on dom, the element doesn't exists yet on maps.即使在安装到 dom 后读取,该元素也不存在于地图上。 So, to solve this issue, we need to add a dom listener:所以,要解决这个问题,我们需要添加一个 dom 监听器:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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