简体   繁体   English

React.js - 在单击事件上查找映射元素的 ID

[英]React.js - Finding ID of a mapped element on click event

I'm trying to find the id of the current element, so that when i do an onClick , i can manipulate just the mapped element I have clicked.我试图找到当前元素的 id,这样当我执行onClick ,我可以只操作我点击的映射元素。

test onClick测试点击

const testClick = (event) => {
    console.log(event.person.id)
}

data:数据:

{
  "ExampleData": [
    {
      "id": 0,
      "name": "Joe Doe",
      "email": "joedoe@gmail.com"
    },
    {
      "id": 1,
      "name": "John Smith",
      "email": "johnsmith@example.com"
    },
]

} }

mapping:映射:

const data = exampleData.ExampleData

 {(data|| {}).map((person, i) => {
                return (
                    <DataContainer testClick={testClick} person={person}/>
                )
            })}

that maps the DataContainer child as many times as there are items in the array of objects.映射 DataContainer 子对象的次数与对象数组中的项目一样多。

But now, I'm trying to have an onClick that detects the specific mapped item i have pressed.但是现在,我正在尝试使用 onClick 来检测我按下的特定映射项目。 As youy can see I'm passing the testClick function to DataContainer, and inside there I'm trying console log the current ID of the user I have pressed.正如你所看到的,我正在将testClick函数传递给 DataContainer,在那里我正在尝试控制台记录我按下的用户的当前 ID。

const testClick = (e) => {
    console.log(e.id)
}

For example:例如:

onClick - if ID === currentID --- do something 

add an arrow function as handler for the click event and pass the id as parameter :添加一个箭头函数作为单击事件的处理程序并将 id 作为参数传递:

 testClick={()=>testClick(person.id)}

if you need also the event you could do :如果你还需要你可以做的事件:

 testClick={(event)=>testClick(event,person.id)}

and

 const testClick = (event,id) => {
   console.log(event, id)
}

只需使用这个testClick={()=>testClick(person.id)}并在 testclick 函数中获取被点击的 ID ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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