简体   繁体   English

反应功能组件 OnClick 事件 Scope 错误

[英]React Functional Component OnClick Event Scope Error

While creating an array of table data, I'm trying to pass the current ID of an image into a function using an onClick event.在创建表数据数组时,我正在尝试使用 onClick 事件将图像的当前 ID 传递到 function 中。 What am I doing wrong here?我在这里做错了什么? I had the impression a simple solution such as this.id or an event handler would function correctly.我的印象是一个简单的解决方案,例如 this.id 或事件处理程序,function 会正确。 Any ideas?有任何想法吗? Thank you!谢谢!

        function deleteRecord(event)
        {
               alert(event.target.id);       
        }

        let j = 0; 
        for(let i in dataRes)
        {
            j++;
            arr.push
            (
                    <tr>
                        <td><div><img id={j} src={"RANDOM IMAGE"} onClick={(event)=>deleteRecord(event)} /><span id={"item"+j}>{DATA}</span></div></td>
                        <td>{DATA}</td>
                        <td>{DATA}</td>
                    </tr>
            );
        }

You're passing in the onClick event into the function, when all you need to pass is the value of j .您将 onClick 事件传递到 function 中,此时您只需要传递j的值。 However, we want to pass the value of j at the point in the loop, so we need to make a copy of j before passing it in.但是,我们想在循环中传递j的值,所以我们需要在传递之前复制j

So right after j++;所以在j++; , we need to create a new copy let j_copy = j; ,我们需要创建一个新副本let j_copy = j;

Then your onClick function should be:那么你的 onClick function 应该是:

onClick={()=>deleteRecord(j_copy)}

and your deleteRecord function:和你的deleteRecord function:

function deleteRecord(index)
{
      alert(index);    // alerts the value of j_copy 
}

This hard-codes the value of j each time the loop runs.这会在每次循环运行时对 j 的值进行硬编码。 Note that each time the loop runs, a new HTML fragment with a different onClick handler gets generated with that hard-coded value.请注意,每次循环运行时,都会使用该硬编码值生成具有不同 onClick 处理程序的新 HTML 片段。 So the first time, it's equal to onClick={()=>deleteRecord(1)} , the second time it's onClick={()=>deleteRecord(2)} , and so on.所以第一次等于onClick={()=>deleteRecord(1)} ,第二次等于 onClick={ onClick={()=>deleteRecord(2)} ,以此类推。

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

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