[英]How to separate input field values in React?
I have a list of inputs that are generated based on the number of items in an array: 我有一个基于数组中项目数生成的输入列表:
const itemInputs = items.map(
item => <Input key={item} value={itemInput} onChange={event => this.updateItem(event)} />,
);
Here is what my updateItem function looks like: 这是我的updateItem函数的样子:
updateItem(event) {
this.setState({
itemInput: event.target.value,
});
}
So if there are two items in my array, then two input fields will be generated, like so: 因此,如果我的数组中有两个项目,那么将生成两个输入字段,如下所示:
But when I enter a value for the first input field, that same value appears in the second input field, like so: 但是当我输入第一个输入字段的值时,第二个输入字段中会出现相同的值,如下所示:
How can I prevent this from happening? 我怎样才能防止这种情况发生? I want each input field to retain its own value.
我希望每个输入字段保留自己的值。
Here is one way to do that 这是一种方法
const items = ['firstName', 'lastName']; const itemInputs = items.map( name => <Input key={name} name={name} value={this.state[name]} onChange={event => this.updateItem(name, event)} />, ); updateItem = (name, event) => { this.setState({ [name]: event.target.value }); }
Well, I assume you are putting all the inputs in one component. 好吧,我假设您将所有输入放在一个组件中。 And component can have only 1 state.
组件只能有1个状态。
In other words, you are changing the value of itemInput
, and it effects all inputs because ypu declared that their value would be itemInput
of the same component of all. 换句话说,您正在更改
itemInput
的值,并且它会影响所有输入,因为ypu声明它们的值将是itemInput
的相同组件的itemInput
。
What you can do is make a new component for input, and call it instead. 你可以做的是为输入创建一个新组件,然后调用它。 That way you will have state for every single input.
这样你就可以获得每一个输入的状态。
Hope that helps. 希望有所帮助。 Good luck
祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.