簡體   English   中英

在React Js中的數組索引上添加自定義onClick事件監聽器

[英]Add Custom onClick Event Listener on Array Index in React Js

我有一個全局定義的數組,試圖將自定義事件偵聽器添加到數組中存在的每個元素

var item = ["A", "B", "C", "D"]
export default class Test extends React.Component{
   componentWillMount() {
      for (var i = 0; i < item.length; i++) {
         item[i].addEventListener("click",this.bindClick.bind(this,i));
      }
   }

    bindClick(i){
        console.log("check", i)
    }
}

我已經嘗試了上面的代碼,但出現此錯誤

Uncaught TypeError: item[i].addEventListener is not a function

請幫助我,在此先感謝;

您不能向項目添加偶數偵聽器,因為它們是字符串類型=>,它們沒有'addEventListener'方法。 但是您可以使用React元素包裝數組元素,可以輕松地將事件偵聽器綁定到:

const arrayItems = [<div key=“0” onClick={this.bindClick}>A</div>];

因此您的組件將如下所示:

export default class Test extends React.Component {
    constructor() {
        super(props);

        this.bindClick = this.bindClick.bind(this);
    }

    bindClick() {
        console.log(“hello!”)
    }

    render() {

        const arrayItems = [
            <div key=“0” onClick={this.bindClick}>A</div> ,
            <div key=“1” onClick={this.bindClick}>B</div>
        ];

        return arrayItems;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM