[英]How can I add styling to an event listener in an class component in React?
[英]How can I add event listener for an object?
在為該對象編寫成員函數時,如何將addEventLisener
到該對象時遇到麻煩。
我有一個名為Grid
的類,該類具有創建HTML div
元素的成員函數create
。 現在,我想向該div
添加一個事件監聽器,該事件監聽器等待click
。 這是代碼。
請注意,我還有另一個網格成員函數的update
。
Grid.prototype.create = function(index) {
var newnode = document.createElement("div");
newnode.setAttribute("class", "grid");
newnode.setAttribute("id", "grid" + index);
newnode.style.width = this.width + "px";
newnode.style.height = this.height + "px";
document.getElementById("whole").appendChild(newnode);
newnode.addEventListener("click", function() {
if (this.live) {
this.live = false;
} else {
this.live = true;
}
this.update(index);
}, false);
this.update(index);
};
問題是, this
代表了addEventListener
塊內的HTML DIV Object
,但我需要將其作為Grid Object
以便可以調用update
函數。
如何解決這個問題呢? 還是在創建包含對象的div
時添加對象的偵聽器的另一種方法?
只需使用在事件處理程序范圍之外聲明的變量
Grid.prototype.create = function(index) {
var grid = this,
newnode = document.createElement("div");
newnode.className = "grid";
newnode.id = "grid" + index;
newnode.style.width = this.width + "px";
newnode.style.height = this.height + "px";
newnode.addEventListener("click", function() {
grid.live = !grid.live;
grid.update(index);
}, false);
document.getElementById("whole").appendChild(newnode);
this.update(index);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.