Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

javascript - 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.

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.

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?

question from:https://stackoverflow.com/questions/65927708/how-to-return-id-from-onclick-in-a-function-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...