简体   繁体   中英

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. 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. If I do it with the src it works.

I hope you can help me with this. Thanks!

You can just pass the item's index (that's what usually done):

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>
  );
};

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