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

React中如何用单个函数处理map渲染的动态输入框onChange事件

统一处理动态输入框变更的实现方案

可以实现单函数统一处理所有输入框的变更,核心逻辑是在触发onChange时传入当前输入对应要修改的字段名和行索引,函数内通过这两个参数精准定位并更新对应数据即可,具体实现步骤如下:

  • 第一步:修正渲染逻辑中的onChange参数,补全事件对象,新增字段名入参,同时将输入框的value绑定改为从组件state读取(props为只读属性,不能直接修改,需要将接口返回的setsList同步到组件state中存储)
    // 组件state需提前同步props.setsList,比如在componentDidMount中执行 this.setState({formList: this.props.setsList})
    this.state.formList.map((codeset, index) => (
         <Table.Row key={codeset.code_system_id}>
           <Table.Cell>{index + 1}</Table.Cell>
           <Table.Cell>{codeset.name}</Table.Cell>
           <Table.Cell>
             <Input
               type='text'
               className='form-control'
               value={codeset.code}
               placeholder={translateText('Code')}
               onChange={(e) => this.handleInputChange(e, index, 'code')}
               style={{ height: '70%' }}
             />
           </Table.Cell>
           <Table.Cell>
             <Input
               type='text'
               className='form-control'
               value={codeset.description}
               placeholder={translateText('Code Description')}
               onChange={(e) => this.handleInputChange(e, index, 'description')}
               style={{ height: '70%' }}
             />
           </Table.Cell>
         </Table.Row>
    ))
    
  • 第二步:实现通用的输入变更处理函数,遵循React不可变更新原则修改state数据
    handleInputChange = (e, index, fieldName) => {
      const inputValue = e.target.value;
      // 浅拷贝原数组,避免直接修改state
      const newFormList = [...this.state.formList];
      // 精准更新对应索引项的对应字段
      newFormList[index] = {
        ...newFormList[index],
        [fieldName]: inputValue
      };
      this.setState({ formList: newFormList });
    }
    
  • 第三步:后续提交数据时,直接读取this.state.formList传给后端接口即可。如果后续新增其他字段的输入框,仅需要在新增输入的onChange中传入对应字段名,不需要额外新增处理函数,可直接复用当前通用函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:09:01