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

如何在React Material UI的Autocomplete组件onChange事件中传递index

解决方法

步骤1:修改Autocomplete组件的onChange绑定,在回调中传入当前遍历的index

在map渲染Autocomplete时,把事件对象、选中值、当前index一起传入处理函数,同时建议给id加上index避免多个组件id重复:

<Autocomplete
  id={`itemNumber-${index}`}
  value={element.itemNumber}
  options={this.state.Data}
  getOptionLabel={option => option}
  onChange={(event, value) => this.onChangeHandleInput(event, value, index)}
  renderInput={params => (
    <TextField {...params} fullWidth />
  )}
/>

步骤2:修改onChangeHandleInput处理函数,接收index参数动态更新对应项

同时建议对要修改的项做浅拷贝,避免直接修改原状态的引用导致异常:

onChangeHandleInput  = (event, value, index) => {            
  const currentItem = [...this.state.currentItem];
  currentItem[index] = {
    ...currentItem[index],
    itemNumber: value
  }
  this.setState({ currentItem });
}

额外优化点

你代码中const currentItem= Object.values(this.state.currentItem);是多余操作,this.state.currentItem本身就是数组,直接遍历即可,不需要调用Object.values。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:09:03