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 badges2 Answers
Reset to default 14You 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
版权声明:本文标题:javascript - Getting the id of a clicked element from rendered list - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738472069a2088650.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论