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

React array.map绑定点击事件仅获取数组最后一项问题咨询

问题产生原因

你在事件绑定时直接执行了状态更新函数,而非传递点击时才触发的函数引用:

  • 你写的onClick={ onClick(item.title) } 会在组件渲染、map遍历的过程中立刻同步执行onClick(item.title),而不是等待用户点击Link时才触发
  • 遍历数组时会按顺序执行所有项的onClick(item.title)调用,后续调用会覆盖之前的状态值,最终状态只会保留最后一次调用传入的数组末尾项的title
修复方法

将onClick绑定的内容改为箭头函数包裹,仅在用户实际点击时才执行状态更新逻辑:

<Link 
  to="/checkout"  
  className="btn btn-lg button-color"  
  onClick={() => onClick(item.title)}
>
  Give <i className="bi bi-arrow-right"></i>
</Link>

额外优化建议

你当前遍历生成的所有输入框都使用了相同的id="enterAmount",HTML中DOM的id属性不允许重复,会导致点击label无法正确聚焦对应输入框,建议修改为带唯一标识的格式:

<input 
  type="text" 
  className="form-control" 
  id={`enterAmount-${item.id}`} 
  placeholder='Enter Amount' 
  aria-describedby="enterAmount" 
  onChange={e => {setInput(e.target.value);onChange(e.target.value);}} 
/>
<label htmlFor={`enterAmount-${item.id}`}>Enter Amount</label>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:36:05