最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: e.target.getAttribute ("id") works 20% of the time? - Stack Overflow

programmeradmin1浏览0评论

I'm new to React and been trying to fix this for hours. I'm trying to get the id of the button which is clicked But this only gets the id around 20% of the time and the rest it returns nulltext. I have no idea what else to do. I have tried different binding methods but haven't been able to make it work.

I simplified the code here and put it below.

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;

Console Image: The buttons should give the id xxxtext, yyytext or zzztext depending on the button clicked but this only works 20% of the time. The rest it returns nulltext and after some clicks it returns again the proper id:

I'm new to React and been trying to fix this for hours. I'm trying to get the id of the button which is clicked But this only gets the id around 20% of the time and the rest it returns nulltext. I have no idea what else to do. I have tried different binding methods but haven't been able to make it work.

I simplified the code here and put it below.

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;

Console Image: The buttons should give the id xxxtext, yyytext or zzztext depending on the button clicked but this only works 20% of the time. The rest it returns nulltext and after some clicks it returns again the proper id:

Share Improve this question edited Aug 21, 2020 at 6:26 Daniel Widdis 9,16013 gold badges48 silver badges68 bronze badges asked Sep 25, 2018 at 5:46 B GamB Gam 1131 silver badge6 bronze badges 3
  • i am not getting your issue. What do you mean 20% of time? Please describe in meaningful way – Hemadri Dasari Commented Sep 25, 2018 at 5:51
  • 1 Question is, why are you mutating DOM when you are using React? – Rajesh Commented Sep 25, 2018 at 5:55
  • We are moving a website that was made in normal html, css and js to react. We want to display different divs depending on the button chosen. I'm afraid I dont know any other way to do it. Any pointers appreciated. – B Gam Commented Sep 25, 2018 at 6:08
Add a ment  | 

2 Answers 2

Reset to default 12

Using e.currentTarget.id should solve your issue.

e.target holds the element that you clicked on, but e.currentTarget will hold the element where you have bind the handler.

When you use e.currentTarget:

<button className="popup" id="xxx" onClick={this.popupnewshow}>
   <div className="popuptitle">xxx</div><!-- clicking on here: 
    e.currentTarget.id is xxx -->
</button>

When you use 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>

In general better to avoid direct DOM manipulation like remove. Also you can get the id directly rather than from the event:

const toggleItem = (arrayOfObjects, objectId) => {
  //some implementation of toggle object's vislble prop based on id property in array 
}

class Popupright extends React.Component {

  state = {
    popups: [
      {id: 'xxx', text: 'xxxtext', visible: false},
      {id: 'yyy', text: 'yyytext', visible: false},
      ...
    ]
  }

  togglePopup = id => {
    this.setState(prevState => ({
      popups: [...toggleItem(prevState.popups, id)]
    })
  }

  render() {
    return (
      <table>
        ...
        <td>
          <button onClick={() => this.togglePopup('xxx')} />
        </td>
        ...
      </table>

      <div className="popupsWrap">
        {this.state.popups.map(popup => {
          if (popup.visible) {
            return (
              <div className="poprighttext">{popup.text}</div>
            )
          }
        }}
      </div>
...
发布评论

评论列表(0)

  1. 暂无评论