简体   繁体   English

在reactjs组件状态下动态生成属性

[英]Dynamically generating properties in a reactjs component's state

I have very large form, I would like to have a state that saves all of the user's input data, in different attributes named after the form. 我有一个非常大的表单,我希望有一个状态,该状态将用户的所有输入数据保存在以表单命名的不同属性中。

So lets suppose I have a form with name, age and email. 因此,假设我有一个包含姓名,年龄和电子邮件的表格。 I want all of that to be saved in state called value. 我希望所有这些都保存在称为值的状态中。 So once the form is filled I would have this.state.value[name] , this.state.value[age] and this.state.value[email] . 因此,一旦表单被填写,我将拥有this.state.value[name]this.state.value[age]this.state.value[email]

However this does not work, I get an error when I try to store the form's input data in that matter. 但是,这不起作用,在此情况下尝试存储表单的输入数据时出现错误。

Here is the code for handleChange(): 这是handleChange()的代码:

handleChange(e) {
     //this.setState({value[e.target.name]: e.target.value}); //does not work
     this.setState({[e.target.name]: e.target.value}); //works!
}

So how could I store the values in from the forms under a state attribute? 那么,如何将状态表单中的值存储在state属性下呢?

Thanks! 谢谢!

What if you do it like this: 如果您这样做,该怎么办:

const value = Object.assign({}, this.state.value)
value[e.target.name] = e.target.value
this.setState({ value })

value[e.target.name] is not a valid key. value[e.target.name]不是有效的键。 What you are attempting is to perform an update of the states value property, for which I would recommend something like immutability-helper . 您试图执行的是对States value属性的更新,为此我建议使用immutability-helper之类的东西。

In which case your update would look like: 在这种情况下,您的更新将如下所示:

this.setState({value: update(this.state.value, {[e.target.name]: {$set: e.target.value})})

Note that the use of Object.assign to create a copy as posted in another answer (+1) will achieve the same thing and is perfectly reasonable in this case. 请注意,使用Object.assign创建另一个答案(+1)中发布的副本将实现相同的目的,并且在这种情况下完全合理。 The immutability helper, however, is a useful tool to have for more complex updates. 但是,不变性帮助器是进行更复杂更新的有用工具。

First, I would like to point out that value is not defined in that method, which could be why you get the error (you never specified the exact error). 首先,我想指出的是,该方法中未定义value ,这可能就是为什么您会得到错误(您从未指定确切的错误)的原因。

You would typically store the values as they are updated. 您通常会在更新值时存储它们。

<input onChange={ e => this.setState({name: e.target.value}) />

Then, when the form is submitted, you would have access to all of the values in the state object. 然后,提交表单后,您将可以访问状态对象中的所有值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM