You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React子组件中传递并使用map循环的索引?

解决方法

要在Row子组件中使用map循环的index,只需两步操作:

1. 父组件传递index属性

修改父组件的map渲染代码,把循环得到的index作为props传给Row组件:

<tbody>
    {data.map((item, index) => (
      <Row key={index} item={item} deleteMe={deleteChild} index={index} />
    ))}
</tbody>

2. 子组件接收并使用index

在Row子组件中接收index属性,然后在对应位置渲染(如果需要从1开始计数,就给index加1):

const Row = ({ item, deleteMe, index }) => {
  return (
    <tr>
      <td>{index + 1}</td> {/* 从0开始显示就直接写 {index} */}
      <td>{item.exerciseName}</td>
      <td>{item.instructions}</td>
    </tr>
  );
};

更新
感谢所有解答,已通过各位建议成功显示索引。

内容的提问来源于stack exchange,提问作者MeLlmaoEphteban

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 12:39:53