简体   繁体   中英

Handle Click Event in a Stateless component and inside a map function

I am using ReactJs and I have two stateless components:

The parent component receive a list of projects

{currentProjectData.map((project) => (
    <ProjectItem
      key={project.projectid}
      id={project.projectid}
      project={project}
    />
  ))}

and the child component receive the key

 return (
    <Card key={id} elevation={5} className={classes.root}>
      <Box
        borderLeft={componentItem.borderLeftValue}
        borderColor={componentItem.borderColorValue}
        onMouseOver={handleChangeOnMouseEnter}
        onMouseLeave={handleChangeOnMouseLeave}
      ></Card>)

I am having trouble trying to handle click event when someone clicks in the card i need the key

 const handleClick = (key) => {
   console.log(key);
  };

I put click event inside Card

<Card
  key={id}
  elevation={5}
  className={classes.root}
  onClick={handleClick(id)}
>

but the click event trigger when I move the cursor inside the card

在此处输入图片说明

Where should I handle the click event (Parent Component or Child Component) and how?

It needs to be on Card, what you pass to handleClick depends upon how you use props in child component, you can pass key or id. Syntax can be props.key or props.id as well if you are not destructuring props.

return (
    <Card key={id} elevation={5} className={classes.root} onClick={()=>handleClick(id)}>
      <Box
        borderLeft={componentItem.borderLeftValue}
        borderColor={componentItem.borderColorValue}
        onMouseOver={handleChangeOnMouseEnter}
        onMouseLeave={handleChangeOnMouseLeave}
      ></Card>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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