从html调用onClick React函数

时间:2019-07-02 06:43:48

标签: javascript html reactjs bing-maps

我使用带有自定义信息框的Bing地图。信息框还包含我要执行关闭功能的自定义关闭图标。 我已经尝试了多种方法,但未执行clearInfoBox函数。

clearInfoBox() {
   console.log("test");
}

var infoboxTemplate = 
 `<div style="margin-top:0px; margin-left:20px;">
    <a href="javascript:void(0)" onClick="{this.clearInfoBox}"><img style="float: right;" src="${closeIcon}"/></a>
  </div>`

this.centerOfSearchInfoBox = new window.Microsoft.Maps.Infobox(new window.Microsoft.Maps.Location(this.centerOfSearch.latitude, this.centerOfSearch.longitude), {
    htmlContent: infoboxTemplate,
  });

  this.centerOfSearchInfoBox.setMap(map);

2 个答案:

答案 0 :(得分:0)

尝试将clearInfoBox函数更改为常量。这样,您将不需要在构造函数中绑定它。

然后将其作为道具传递给模板变量。

代码应如下所示:

clearInfoBox = () => {
   console.log("test");
}

const infoboxTemplate = (clearFn) => 
 `<div style="margin-top:0px; margin-left:20px;">
    <a href="javascript:void(0)" onClick={clearFn}><img style="float: right;" src="${closeIcon}"/></a>
  </div>`

this.centerOfSearchInfoBox = new window.Microsoft.Maps.Infobox(new window.Microsoft.Maps.Location(this.centerOfSearch.latitude, this.centerOfSearch.longitude), {
    htmlContent: infoboxTemplate(this.clearInfoBox),
  });

this.centerOfSearchInfoBox.setMap(map);

此外,请勿在onChange处理程序周围使用引号。

答案 1 :(得分:0)

也许这会对您有所帮助。 首先是html onclick而不是onClick

var infoboxTemplate = 
 `<div style="margin-top:0px; margin-left:20px;">
    <a href="javascript:void(0)" onclick="onClickInfor()"><img style="float: right;" src="${closeIcon}"/></a>
  </div>`

并添加onClickInfor方法

constructor() {
  ...
  window.onClickInforBox = this.clearInfoBox.bind(this)
}

并在卸载组件时删除onClickInforBox

componentWillUnmount() {
  window.onClickInforBox = undefined
}
相关问题