简体   繁体   中英

React getting the ID of clicked button

I have 5 clickable links, each with unique ID. I am trying to get the ID of the link that was clicked. I have tried two methods but neither work as I would like.

Inside render I have:

this.state.data.map((dynamicData, key) =>
  <a href={"/#/template"} id={dynamicData.id} onClick={() => this.reply_click(this.id)}>{dynamicData.name}</a>
  <a href={"/#/addTeams"}><button type="button" class="btn-lisa">Edit</button></a>

Basic method that returns undefined. What am I doing wrong?:

reply_click(clicked_id) {
  console.log(clicked_id);
}

Using an arrow function will maintain the context of this from the outside, which won't be the this you want. You could try to use a regular function ( function () { } ) instead, but I'm not sure if this will be what you want or not there either.

You can, however, definitely use e.target.id to get what you want:

onClick={e => this.reply_click(e.target.id)}

That said, you should really avoid creating functions inside of things as it can create significant performance issues. It's much better to just create a function and pass it in:

// somewhere above
const handleClick = e => this.reply_click(e.target.id);

// attribute
onClick={handleClick}

you can do this

<a href={"/#/template"} id={dynamicData.id} onClick={() => this.reply_click(dynamicData.id)}>{dynamicData.name}</a>

or another way

<a href={"/#/template"} id={dynamicData.id} onClick={this.reply_click}>{dynamicData.name}</a>



reply_click(event) {
    console.log(event.target.getAttribute('id'))
}
this.reply_click(this.id)

this is your component scope, which means every attribute you defined in your component can be accessed by this . Probably you did not define id in this component.

You probably wanna do

 this.reply_click(dynamicData.id)

instead.

The this inside the arrow function is the same as the this outside it. The onclick is already aware of the correct this , so use it like this:

onClick={this.reply_click(this.id)}

Try this code. The code you have provided doesn't work because this is bound to the current React component, instead you could access id of the clicked element using e.target.id :

this.state.data.map((dynamicData, key) => {
  <a href="/#/template" id={dynamicData.id} onClick={(e) => this.reply_click(e.target.id)}>{dynamicData.name}</a>
  <a href="/#/addTeams"><button type="button" class="btn-lisa">Edit</button></a>
})

Unrelated, but still I want to note that you don't have to use <a href={"blah"} instead you can use <a href="blah" because the last one uses a string contant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM