for (let menuname of this.tabsdata[reqmenuitem]) {
content.push(<Anchor className="toblack" onclick={this._fetchTabData(this)}>{menuname.name}</Anchor>);
}
此处_fetchTabData
会在页面呈现时触发,请指导我如何将onclick
侦听器正确附加到相应的数组元素
答案 0 :(得分:0)
在你的情况下,你正在调用函数_fetchTabData
(结果传递给onClick
我假设你的函数返回undefined
所以onClick
你传递undefined
)但对于onClick
,您应该传递对函数的引用。您可以使用arrow function
或.bind
for (let menuname of this.tabsdata[reqmenuitem]) {
content.push(
<Anchor
className="toblack"
onClick={() => { this._fetchTabData(menuname) } }
>
{menuname.name}
</Anchor>
);
}
答案 1 :(得分:0)
首先,将您的_fetchTabData
实施更改为以下内容:
_fetchTabData(menuname) {
return (event) => {
// Do what you need
console.log(menuname);
};
},
然后,像这样称呼它
for (let menuname of this.tabsdata[reqmenuitem]) {
content.push(<Anchor className="toblack" onclick={this._fetchTabData(menuname)}>{menuname.name}</Anchor>);
}
答案 2 :(得分:-1)
.getElementById('container').children
----使用parent的.children属性将元素放入数组中。for()
.addEventListener(type,function)
循环遍历数组
// PURE JS
<!DOCTYPE html>
<html>
<head>
<script>
click = {
changecolor: (e)=>{
e.target.style.color = "red";
}
};
init = ()=>{
var childs = document.getElementById('container').children;
for(var i=0; i < childs.length; i++){
childs[i].addEventListener('click', click.changecolor);
}
}
document.addEventListener('DOMContentLoaded', init);
</script>
</head>
<body>
<div id="container">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
</body>
</html>