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

React如何将多输入框值存入state对象的数组字段,避免重复函数?

有两种常用的简洁实现方案,都不需要写多个重复的处理函数:

方案1:通过索引标识输入框,共用同一个处理函数

给每个颜色输入框添加自定义索引标识,在回调中根据索引更新数组对应位置的值:

// 组件部分代码
<TextField data-index="0" onChange={handleColorChange} />
<TextField data-index="1" onChange={handleColorChange} />
<TextField data-index="2" onChange={handleColorChange} />

// 处理函数代码
const handleColorChange = (e) => {
  const index = Number(e.target.dataset.index)
  // 拷贝原数组避免直接修改状态
  const newColors = [...info.colors]
  newColors[index] = e.target.value
  setInfo({...info, colors: newColors})
}

方案2:使用高阶函数绑定索引

如果用的是支持直接传参的UI库(比如Material UI的TextField),可以直接通过高阶函数绑定索引,不需要加自定义属性:

// 处理函数代码
const handleColorChange = (index) => (e) => {
  const newColors = [...info.colors]
  newColors[index] = e.target.value
  setInfo({...info, colors: newColors})
}

// 组件部分代码
<TextField onChange={handleColorChange(0)} />
<TextField onChange={handleColorChange(1)} />
<TextField onChange={handleColorChange(2)} />

如果颜色输入框的数量不固定,还可以通过循环生成输入框,后续增减数量只要修改循环长度即可:

{Array.from({length: 3}).map((_, index) => (
  <TextField key={index} onChange={handleColorChange(index)} />
))}

补充提醒:你之前写的setInfo(...info, firstName:e.target.value)存在语法错误,扩展的状态对象需要包裹在大括号内,正确写法是setInfo({...info, firstName: e.target.value})


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:48:04