将 onclick 函数添加到包裹在 `div` 中的一组 `cards`

Adding an onclick function to a group of `cards` wrapped in a `div`

我有一个反应组件,我需要在单击组中的任何卡片时添加一个动作。问题是我需要能够确定单击了哪张卡片才能正确执行我的操作。我尝试向每张卡片添加 keyindex,但我无法弄清楚如何捕获点击了哪张卡片这是我的代码:

<>
      <div className={styles.cardContainer}>
        <div
          className={`card-group ${styles.cardGroups}`}
  >>>>>   onClick={(e) => console.log(e.target)}
        >
          <Card index={type} className={styles.observationsType}>
            <div className="">
              <h2 className={styles.title}>{title}</h2>
              <div className={styles.limits}>
                {!!lim && !!lim.label.upper ? `Upper Limit: ${lim.label.upper}` : ""}
              </div>
              <div className={styles.limits}>
                {!!lim && !!lim.label.lower ? `Lower Limit: ${lim.label.lower}` : ""}
              </div>
            </div>
          </Card>
          <Card index={type} className={styles.observationsDateCard}>
            <div className={styles.date}>
              <div>{!!obs.recordedDate && moment(obs.recordedDate).format("L")}</div>
              <div>{!!obs.recordedDate && moment(obs.recordedDate).format("LT")}</div>
            </div>
          </Card>
          <Card index={type} className={`text-center ${styles.observationLatest}`}>
            <div className={styles.latest}>
              {value}
              <div>{obs.unit}</div>
            </div>
          </Card>
        </div>
      </div>
    </>

您会在 card-group div 中看到我添加了带有 console.log 的 onClick 函数。我为每张卡片添加了一个索引,其中包含每张卡片中信息组的名称,希望以此名称为目标。但这不起作用。无论如何我可以做到这一点 属性 或者更好的方法来做到这一点?

与其将卡片渲染为独立组件,不如尝试将它们的数据存储在数组中,然后使用 map 函数渲染卡片。然后,您可以给每张卡片一个 onClick 事件,并将索引作为参数,这样您就知道点击了哪张卡片。像这样:

创建卡片数组

const cards = [
    {
        name: "card 1",
        // some other data
    },
    {
        name: "card 2",
        // some other data
    },
    {
        name: "card 3",
        // some other data
    }
]

创建一个函数来捕获点击的卡片:

function onCardClick(index) {
    const selectedCard = cards[index];

    // do some stuff with the clicked card
}

渲染数组中的卡片:

{cards.map((card, index) => <Card onClick={() => onCardClick(index)} />)}