reactjs - 当输入位于 map 函数内部时,如何获取 onChange 输入的值

标签 reactjs

我想在 map 循环函数内获取某些输入变化的值。这是我的组件:

import React, { Component } from "react";

class ArrayComponent extends Component {
 constructor(props) {
 super(props);
 this.state = { objects: [] };
 }

  handleChange(index, id, e) {

  // what to put here ?
  // want to have a state like :
  // [{index: e.target.value, key: id}, {index: e.target.value, key: id}, ...]

   }
 render() {
  return (
     <Form onSubmit={this.onSubmit}>
      {items.map((item, index) => (
        <div>
          {item.name}
          <input
            key={index}
            value={this.state.objects[index]}
            onChange={this.handleChange.bind(this, index, item.id)}
          />
      </div>
    ))}
       <Button>
         Update 
       </Button>
     </Form>
    );
  }
  }

  export default ArrayComponent;

我想要一个这样的状态: [{index: e.target.value, id: id}, {index: e.target.value, id: id}, ...] 这意味着如果它们是我想要的四个输入对于四个输入具有如上所述的状态。

最佳答案

您是否正在寻找这样的东西:

constructor(props) {
 super(props);
 this.state = { objects: {} };
}

handleChange(event, index, id) {
   this.setState((state) => {
    const newObject = {...state.objects};
    newObject[`${index}`] = {value: event.target.value, key: id}
    return {objects: newObject }
   });
}

render() {
  return (
     <Form onSubmit={this.onSubmit}>
      {items.map((item, index) => (
        <div>
          {item.name}
          <input
            key={item.id}
            value={this.state.objects[`${index}`]?.value || ''}
            onChange={(event) => this.handleChange(event, index, item.id)}
          />
      </div>
    ))}
       <Button>
         Update 
       </Button>
     </Form>
    );
  }
}

您应该避免将 map index值设置为组件键。所以我删除了索引,只使用项目 id 作为关键属性。


编辑 - 删除索引

您可以一起删除索引:

handleChange(event, id) {
   this.setState((state) => {
    const newObject = {...state.objects};
    newObject[`${id}`] = {value: event.target.value, key: id}
    return {objects: newObject }
   });
}

//........

value={this.state.objects[`${item.id}`]?.value || ''}
onChange={(event) => this.handleChange(event, item.id)}

关于reactjs - 当输入位于 map 函数内部时,如何获取 onChange 输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69227067/

相关文章:

reactjs - Jest 在 React 中测试异步图像上传

javascript - 转换多个 JSX 文件

javascript - 在浏览器的本地存储中保留旧数据

javascript - 我尝试运行命令 "npm run start ",它在 React js 中显示此错误

javascript - 在浏览器关闭时保持用户登录,而不是在刷新时

reactjs - 使用 Apollo 替换 Redux 进行本地状态管理

javascript - React Router (Dom) v4 在输入回车键时重定向到不同的路由

reactjs - Flux/React Complex 可重复使用组件

javascript - 获取数据,函数 Error() { [native code] } <constructor> : "Function"

javascript - 警告 : React. createElement : type should not be null, 未定义、 bool 值或数字