因此,在我的应用程序中,用户可以选择输入数字,例如,如果用户输入为"5〃;则它将添加5个文本输入。至此,我已经成功地循环了textInput。现在,如何在状态中填充或存储值?
My code :
this.state =
{
usersDetails: [{name: "", age: "", gender: "", primary: false}, {name: "", age: "", gender: "", primary: false}]
};
handleChange(i, e) {
const { name, value } = e;
let users = [...this.state.usersDetails];
users[i] = {...users[i], [name]: value};
this.setState({ usersDetails });
console.log(this.state.usersDetails);
}
let items = [];
for (let i = 0; i < this.props.maxSeats; i++) {
items.push(
<TextInput
placeholder="Enter Name"
onChangeText={this.handleChange.bind(this, i)}
value={this.state.userDetails}
/>)
}
在stockoverflow的帮助下,我创建了handleChange函数,但它给出了错误!如何填充值并保存动态表单的状态!
请引导!
handleChange = (value, index,key) => {
this.setState((prevState) => ({
...prevState,
usersDetails: prevState.usersDetails.map((val, mapIndex) => {
if (mapIndex === index) {
val[key] = value;
return val;
}
return val;
}),
}));
};
for (let i = 0; i < this.props.maxSeats; i++) {
items.push(
<TextInput
key={i}
placeholder="Enter Name"
onChangeText={(text) => {
handleChange(text, i,'name'); // here you can pass name,age whatever
}}
value={this.state.userDetails[i].name}
/>,
);
}