我想在 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/