我正在使用一个类来动态生成一个由文本输入组成的表单。在我的状态下,我将把数据存储在一个数组中。我的handleInputChange
函数正在跟踪数据,但它在HandleInputChange方法的list[index][name] = value
部分失败。错误为cannot set property playerName of undefined
。有人能帮我解释一下我是怎么做到的吗?
import React, { Component } from "react";
class Form extends Component {
constructor(props) {
super(props);
this.state = {
playerNames: [],
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange = (e, index) => {
const { playerNames } = this.state;
const { name, value } = e.target;
const list = [...playerNames];
list[index][name] = value;
this.setState({ playerNames: this.list });
};
handleClick = () => {
const { playerNames } = this.state;
this.setState([...this.playerNames, { playerName: "" }]);
};
render() {
const { playerNames } = this.state;
const { noPlayers, handleClick } = this.props;
let multiples = [];
for (var i = 0; i < noPlayers; i++) {
multiples.push(<div></div>);
}
return (
<div>
<form>
<label className="block">
<>
{multiples.map((input, index) => (
<input
key={index}
name="playerName"
className="form-input mt-1 block w-full"
type="text"
placeholder={"Player " + (index + 1)}
value={index.playerName}
onChange={(e) => this.handleInputChange(e, index)}
/>
))}
</>
</label>
<button
className="bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4 border-b-4 border-blue-700 hover:border-blue-500 rounded"
onClick={handleClick}
>
Submit
</button>
</form>
</div>
);
}
}
export default Form;
list[index][name] = value
失败,因为数组中没有初始对象。
假设您希望playerNames类似
[
{ playername: "input1 value" },
{ playername: "input2 value" },
{ playername: "input3 value" },
];
您需要更改
const list = [...playerNames];
list[index][name] = value;
this.setState({ playerNames: this.list });
每次时创建一个包含新对象的新列表
const list = [...playerNames];
list[index] = {[name]:value};
this.setState({ playerNames: list });