javascript - 反应:e.target.getAttribute ("id") 工作 20% 的时间?
问题描述
我是 React 的新手,并试图解决这个问题好几个小时。我正在尝试获取单击的按钮的 id 但这仅在大约 20% 的时间中获取 id,其余的则返回 nulltext。我不知道还能做什么。我尝试了不同的绑定方法,但无法使其工作。
我在这里简化了代码并放在下面。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Popupright extends React.Component {
popupnewshow = (e) => {
let ids = e.target.getAttribute("id") + "text";
console.log(ids)
let elements = document.getElementsByClassName('poprighttext showtext');
while(elements.length > 0){
elements[0].classList.remove('showtext');
};
document.getElementById(ids).classList.toggle("showtext");
};
render() {
return (
<div>
<table className="table-bordered">
<tbody>
<tr className="table-samewidth">
<td className="td-general"><button className="popup" id="xxx" onClick={this.popupnewshow}><div className="popuptitle">xxx</div></button></td>
</tr>
<tr className="table-samewidth">
<td className="td-general"><button className="popup" id="yyy" onClick={this.popupnewshow}><div className="popuptitle">yyy</div></button></td>
</tr>
<tr className="table-samewidth">
<td className="td-general"><button className="popup" id="zzz" onClick={this.popupnewshow}><div className="popuptitle">zzz</div></button></td>
</tr>
</tbody>
</table>
<div id="xxxtext" className="poprighttext">
<p>xxx.</p>
</div>
<div id="yyytext" className="poprighttext">
<p>yyy</p>
</div>
<div id="zzztext" className="poprighttext">
<p>zzz</p>
</div>
</div>
);
}
}
export default Popupright;
控制台图像:按钮应根据单击的按钮提供 id xxxtext、yyytext 或 zzztext,但这仅在 20% 的情况下有效。其余的它返回 nulltext 并在单击后再次返回正确的 id:
解决方案
使用e.currentTarget.id
应该可以解决您的问题。
e.target
保存您单击的元素,但e.currentTarget
将保存您绑定处理程序的元素。
当你使用e.currentTarget
:
<button className="popup" id="xxx" onClick={this.popupnewshow}>
<div className="popuptitle">xxx</div><!-- clicking on here:
e.currentTarget.id is xxx -->
</button>
当你使用e.target
:
<button className="popup" id="xxx" onClick={this.popupnewshow}>
<div className="popuptitle">xxx</div><!-- clicking on here:
there's no id here (the clicked element id) -->
</button>
推荐阅读
- python - Python检查二维列表是否包含另一个列表的数字
- r - 将 p 值添加到平行坐标图 (ggplot) 时出错
- tableau-api - 更改饼图中的标签颜色
- tomcat - 如果多个服务在一个 Tomcat 服务器上运行,这是如何实现的?
- mysql - MySql 添加关系而不创建欺骗
- reactjs - 如何在堆栈导航器(react-navigation 2.X)中卸载先前安装的组件?
- css - 具有背景颜色的自定义块取决于书籍颜色主题
- grpc - Traefik 作为入口控制器 + 服务器 GRPC - 未知:未收到状态
- symfony - 尝试从命名空间“AppBundle\Security\Handler”加载类“OAuthFailureHandler”
- docker - 无法在 Ubuntu 上启动 docker?