首页 > 解决方案 > 反应: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:
控制台图像:按钮应根据单击的按钮提供 id xxxtext、yyytext 或 zzztext,但这仅在 20% 的情况下有效。 其余的它返回 nulltext 并在单击后再次返回正确的 id

标签: javascriptreactjs

解决方案


使用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>

推荐阅读