简体   繁体   English

处理无状态组件和地图函数中的点击事件

[英]Handle Click Event in a Stateless component and inside a map function

I am using ReactJs and I have two stateless components:我正在使用 ReactJs 并且我有两个无状态组件:

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.它需要在 Card 上,您传递给 handleClick 的内容取决于您如何在子组件中使用 props,您可以传递 key 或 id。 Syntax can be props.key or props.id as well if you are not destructuring props.如果您不破坏道具,语法也可以是 props.key 或 props.id。

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

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

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