[英]Cleanest way for allowing HTML's onClick to access a module's function?
Say I have a class:假设我有一个 class:
export default class SubmitModal {
constructor () {
this.element = document.createElement('div')
this.element.classList.add('modal')
this.element.innerHTML = this.generateContentHTML()
}
generateContentHTML () {
return `
<div class='modal-content'>
a bunch of other things
<button onClick={this.submit()}>Submit</button>
</div>
`
}
submit () {
console.log('submitted!')
}
}
What would be the cleanest way for the button
element to access this.submit
? button
元素访问this.submit
的最简洁方式是什么?
I could make the submit
function a global by appending it to the window
variable;我可以通过将
submit
function 附加到window
变量来将其设为全局; however, that seems bad in the long run (if I have two submit functions, etc.).但是,从长远来看,这似乎很糟糕(如果我有两个提交功能等)。
I also realize that I could simply create a button
element and add and event listener to it, but is there any way I could do the same utilizing HTML's onClick
?我也意识到我可以简单地创建一个
button
元素并为其添加事件侦听器,但是有什么方法可以利用 HTML 的onClick
做同样的事情吗?
Thanks谢谢
Don't create it as HTML.不要将其创建为 HTML。 Create the button using
document.createElement()
, then use addEventListener()
to add the class method as the listener.使用
document.createElement()
创建按钮,然后使用addEventListener()
添加 class 方法作为监听器。
export default class SubmitModal { constructor () { this.element = document.createElement('div') this.element.classList.add('modal') this.element.appendChild(this.generateContent()); } generateContentHTML () { let div = document.createElement("div"); div.classList.add("modal-content"); div.innerHTML = `a bunch of other things`; let button = document.createElement("button"); button.innerText = 'Submit'; button.addEventListener("click", () => this.submit()); div.appendChild(button); return div; } submit () { console.log('submitted!') } }
You have to access it with an arrow function to make it work completely correctly:您必须使用箭头 function 访问它才能使其完全正常工作:
<button onClick={() => this.submit()}>Submit</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.