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

React组件中如何在map循环内用console.log打印索引?

这里有两种常见的方式可以在这个map循环里打印索引,顺便帮你修正了代码里的一个小错误(key属性后面多了个多余的反引号):

方式一:组件渲染时打印所有索引

在map的回调函数里直接添加console.log,组件渲染的时候就会逐个输出每个元素的索引:

{projectData.map((_, index) => {
    console.log('当前项目索引:', index);
    return (
        <button
            key={index}
            onClick={() => goToSlide(index)}
            className={index === currentIndex ? 'active slider-button' : 'slider-button'}>
            { `Project ${index + 1}` }
        </button>
    );
})}

方式二:点击按钮时打印对应索引

如果只想在点击按钮的时候打印该按钮对应的索引,可以把console.log放到onClick的回调函数里:

{projectData.map((_, index) => (
    <button
        key={index}
        onClick={() => {
            console.log('点击的按钮索引:', index);
            goToSlide(index);
        }}
        className={index === currentIndex ? 'active slider-button' : 'slider-button'}>
        { `Project ${index + 1}` }
    </button>
))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:12:04