整个想法是让用户在表单中输入并在 JSON 对象中显示他们的输入。在状态下,我有一个数组,里面有另一个数组。
我的 Form.js 看起来像这样,
state= {
groups:[{
typeA:[{}],
typeB:[{}]
}],
credentials: false
};
change = e =>{
this.setState({[e.target.name]: e.target.value})
};
handleSubmit(event) {
event.preventDefault();
this.setState({
credentials: true
});
}
render(){
return(
<div class="classform">
<form >
<label>
Field1:
<br/>
<input type="text"
name="typeA"
placeholder="Type A"
//store it as the first element of the type A
value={this.state.groups.typeA[0]}
onChange={this.change.bind(this)}
/>
//other fields with the same code
后续会把Field2存为A类型的第二个元素 然后,Field3和Field4将存储为2个B型数组
我希望代码给我这样的输出:
"typeA": ["field1 value", "field2 value"],
"typeB": ["field3 value", "field4 value"]}
我是 React 的初学者,我无法将字段值存储在数组状态中。
最佳答案
为了简单起见,我将推荐以下解决方案, 您可以管理不同状态变量中的输入值,并在提交时将它们更改为您想要的输出,而不是在状态中使用嵌套数组。
state = {
field1: '',
field2: '',
field3: '',
field4: '',
}
change = e => {
this.setState({[e.target.name]: e.target.value})
};
handleSubmit(event) {
event.preventDefault();
const { field1, field2, field3, field4 } = this.state;
// This is your output
const output = [{typeA: [field1, field2], typeB: [field2, field3]}];
this.setState({
credentials: true
});
}
render(){
return(
<div class="classform">
<form >
<label>
Field1:
<br/>
<input type="text"
name="field1"
placeholder="Type A"
value={this.state.field1}
onChange={this.change}
/>
</label>
<label>
Field2:
<br/>
<input type="text"
name="field2"
placeholder="Type A"
value={this.state.field2}
onChange={this.change}
/>
</label>
关于javascript - 如何将用户输入的输入保存为 React 中的数组状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56052244/