如何在函数showChildren
中获取onClick事件div.id
的目标?
期望的结果:
div.id
实际结果:
<react></react>
相关剃须刀
iterateNavigationObject: function(item) {
var titleStyle = {
'backgroundColor': 'grey'
};
return (
<div>
<ul>
<li style={titleStyle}>
<div id="asdf" onClick={this.showChildren}>{item.text}</div>//I want the id of this element
<ul>
{item.items.map(this.iterateNavigationSubitems, this)}
</ul>
</li>
</ul>
</div>
);
},
showChildren: function(){
console.log(event.type);//OUTPUT: 'react-click'
console.log(event.target);//OUTPUT: <react></react>
},
更改点击处理程序签名
showChildren: function(event) {
console.log(event.type);//OUTPUT: 'react-click'
console.log(event.target);//OUTPUT: <react></react>
},
解释:
您可能希望这适用于香草 JS。Internet Explorer 提供了一个全局对象 window.event,它引用最后一个事件。在IE9之前,处理程序中没有参数。这仅适用于IE(可能也适用于其他浏览器)。React 使用它自己的合成事件,因此不要指望这会起作用。React 将event
作为第一个参数传递给所有事件侦听器。
无论如何,你不应该在 React 中依赖它,也不应该依赖 vanilla JS。始终接受event
作为函数参数。
编辑
要传递 ID,请使用高阶函数,该函数返回实际的事件侦听器。 更新对此的调用
<div onClick={this.showChildren("asdf")}>{item.text}</div>
然后,更新侦听器以接受 ID。您可以忽略此解决方案中的先前答案。
showChildren(id) {
return () => {
console.log(id);
}
}