简体   繁体   English

获取 key{index} prop from.map function 在元素被点击的反应

[英]Get key{index} prop from .map function in react of the elemenet being clicked

I have the following code我有以下代码

const Component = () => {

  const [Clicked, setClicked] = useState(false);

  const handleClick = (prop, e) => {
    console.log(prop);
  }

  return (
    <div>
       {arrayCard.map((item, i) => {
          return (<Card 
            onClick={(e) => handleClick(e.target.getAttribute('akey'), e)}
            src={item} 
            akey={i}  />) 
       })}
    </div>
  );

and This is my card component这是我的卡片组件

import React from 'react';
import Image from 'next/image'

const Card = (props) => {

   return (
    <div>
       <button  onClick={props.onClick} >
         <Image
               src={props.src}
               alt="Card Pic"
               width={80}
               height={80}
         />
       </button>
    </div>     
   );
}

As you can see, I have a.map function which gets values from an array and makes card elements.如您所见,我有 a.map function 从数组中获取值并制作卡片元素。 What I want to do is get the specific element being clicked so I thought if I pass a key value I can get the exact element being clicked.我想要做的是获得被点击的特定元素,所以我想如果我传递一个键值,我可以获得被点击的确切元素。

The problem is when I want to get the value of the key prop with the e.target.getAttrinute('akey') returns null.问题是当我想通过 e.target.getAttrinute('akey') 返回 null 来获取 key prop 的值时。 If I do it with the src it works.如果我用 src 来做,它就可以工作。

I hope you can help me with this.我希望你能帮我解决这个问题。 Thanks!谢谢!

You can just pass the item's index (that's what usually done):您可以只传递项目的index (通常是这样做的):

const Component = (props) => {
  const handleClick = (index, e) => {
    console.log(index);
  };

  return (
    <div>
      {props.arrayCard.map((item, index) => {
        return (
          <Card key={index} onClick={(e) => handleClick(index, e)} src={item} />
        );
      })}
    </div>
  );
};

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

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