简体   繁体   English

如何在 function React 中从 onClick 返回 ID

[英]How to return ID from onClick in a function React

I have template setup in a function, and i want it to pass its ID when it's clicked - but somehow the way i have set it up now, it gets clicked as the element is loaded, and i am unable to click it afterwards.我在 function 中有模板设置,我希望它在单击时传递其 ID - 但不知何故,我现在设置它的方式是,它在元素加载时被单击,之后我无法单击它。

import React from 'react'

function PortItem(props){
    return(
        <div className="portItem" onClick={props.click(props.pitem.id)}>
            <img src={props.pitem.src} alt={props.pitem.title}></img>
        </div>
    )
}

export default PortItem

The Console.log logs the correct ID, but does it immediately as the element is loaded. Console.log 会记录正确的 ID,但会在加载元素时立即执行。

import React from 'react'
import portData from "./portData"
import PortItem from "./portItem"

function PortfolioPage() {
    const handleClick = (id) => {
        console.log(id)
    }

    const portItems = portData.map(item => <PortItem key={item.id} pitem={item} click={handleClick}/>)

    return (
        <div>
            {portItems} 
        </div>
    )
}

export default PortfolioPage

How do i make it behave as you would expect it to?我如何让它表现得像你期望的那样? So that when the div with the className "portItem" is clicked, it passes its ID to the handleClick?这样当单击具有类名“portItem”的div时,它会将其ID传递给handleClick?

You need to do:你需要做:

<div className="portItem" onClick={()=>props.click(props.pitem.id)}>

This makes sure that only when we click on the div the handler function is invoked and also the value is passed to the handler.这确保只有当我们单击div时,才会调用处理程序 function 并将值传递给处理程序。

This is a general way to pass the values to handlers, where we basically use a function within a Synthetic Event (in your case onClick )这是将值传递给处理程序的一般方法,我们基本上在Synthetic Event中使用 function (在您的情况下onClick

onEvent={()=>{handlerFunction(value)}}

You are calling it every time the element renders.每次元素呈现时都会调用它。 You should change it to:您应该将其更改为:

<div className="portItem" onClick={() => props.click(props.pitem.id)}>

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

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