admin管理员组

文章数量:1298493

What is the best way to get an id from a clicked element of a list? I am trying to render a list of items and then display an item detail view for the clicked item.

e.g

render() {
  let list = data.map((obj) => {
               return <div key={obj[id]} id={obj[id]} onClick={this.handleClick}></div>         
             });
  return <div>{list}</div>;
}

How do I get the id of the clicked element for use in another component?

What is the best way to get an id from a clicked element of a list? I am trying to render a list of items and then display an item detail view for the clicked item.

e.g

render() {
  let list = data.map((obj) => {
               return <div key={obj[id]} id={obj[id]} onClick={this.handleClick}></div>         
             });
  return <div>{list}</div>;
}

How do I get the id of the clicked element for use in another component?

Share Improve this question edited Jun 2, 2017 at 9:35 Chris 59.5k20 gold badges120 silver badges142 bronze badges asked Jun 2, 2017 at 9:21 devsrdevsr 1031 gold badge1 silver badge4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

You can get the id from the click event directly. No need to bind the variable to the event handler.

render() {
    let list = data.map((obj) => {
       return <div key={obj[id]} id={obj[id]} onClick={this.handleClick}></div>         
    }
    return <div>{list}</div>;
}

handleClick(e){
   console.log(e.target.id);
}

A slightly modified working example:

class MyApp extends React.Component {
  handleClick(e){
    console.log(e.target.id);
  }
  
  render() {
    let data = [0,1,2,3,4];
    let list = data.map((obj, id) => {
      return <div key={obj[id]} id={"id-" + id} onClick={this.handleClick}>{obj}</div>         
    });
    return <div>{list}</div>
  }
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div>

Pass the id in onClick method for each element:

render() {
    let list = data.map((obj) => {
       return <div key={obj.id} id={obj.id} onClick={() => this.handleClick(obj.id)}></div>         
    }
    return <div>{list}</div>;
}

handleClick(id){
   console.log(id);
}

本文标签: javascriptGetting the id of a clicked element from rendered listStack Overflow