【问题标题】:Call onClick React function from html从 html 调用 onClick React 函数
【发布时间】:2019-07-02 06:43:48
【问题描述】:

我使用带有自定义信息框的 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);

【问题讨论】:

  • 点击关闭图标时如何调用函数clearInfoBox()的问题是您尝试从this.clearCenterOfSearchInfoBox调用的函数吗?如果是这样,正常的问题是你没有绑定this.clearCenterOfSearchInfoBox到这个,所以onClick中的this是html元素而不是你的对象
  • 抱歉是复制过去的错误我想在点击关闭图标时调用 clearInfoBox()
  • 由于您使用this,我假设您正在上课。在构造函数中,您需要添加this.clearInfoBox = this.clearInfoBox.bind(this) 或将onClick 更改为onClick="{this.clearInfoBox.bind(this)}" 以在事件中获得对正确this 的引用
  • 方法默认不绑定。如果忘记绑定 this.clearInfoBox 并将其传递给 onClick,则在实际调用该函数时 this 将是未定义的。
  • 是的,我正在上课。当我尝试onClick="{this.clearInfoBox.bind(this)} 时,我得到Cannot read property 'bind' of undefined at HTMLAnchorElement.onclick,当我尝试在构造函数中绑定它时,例如this.clearInfoBox.bind(this); 然后调用它:onClick="{this.clearInfoBox} 什么都没有发生

标签: javascript html reactjs bing-maps


【解决方案1】:

尝试将您的 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 处理程序周围使用引号。

【讨论】:

  • @WeSt 尝试将 onClick 更改为:onClick={${clearFn}}
  • 不再中断但函数也没有执行
【解决方案2】:

也许这会对你有所帮助。 首先在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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 2017-01-30
    • 2021-11-30
    • 2016-02-25
    • 2019-11-06
    • 2017-11-18
    • 2012-06-26
    相关资源
    最近更新 更多