【问题标题】:React.js - Finding ID of a mapped element on click eventReact.js - 在点击事件上查找映射元素的 ID
【发布时间】:2020-12-22 20:04:17
【问题描述】:

我正在尝试查找当前元素的 id,这样当我执行 onClick 时,我可以只操作我单击的映射元素。

测试点击

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

数据:

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

}

映射:

const data = exampleData.ExampleData

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

映射 DataContainer 子对象的次数与对象数组中的项一样多。

但是现在,我正在尝试使用 onClick 来检测我按下的特定映射项。正如你所看到的,我将testClick 函数传递给DataContainer,并在其中尝试控制台记录我按下的用户的当前ID。

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

例如:

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

【问题讨论】:

    标签: javascript arrays reactjs mapping


    【解决方案1】:

    添加箭头函数作为单击事件的处理程序,并将 id 作为参数传递:

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

    如果你还需要你可以做的活动:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2014-09-04
        • 1970-01-01
        • 2013-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多