反应:e.target.getAttribute(“ id”)的工作时间为20%?

B G*_*Gam 1 javascript reactjs id

我是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;
Run Code Online (Sandbox Code Playgroud)

控制台图像:根据所单击的按钮,按钮的ID应该为xxxtext,yyytext或zzztext,但这仅在20%的时间内起作用。其余的它返回nulltext,并且在单击几次之后再次返回正确的id

Bho*_*yar 5

使用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>
Run Code Online (Sandbox Code Playgroud)

使用时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>
Run Code Online (Sandbox Code Playgroud)