Reactjs 动态生成的表单跟踪更改,但返回未定义的
我使用一个类来动态生成一个由文本输入组成的表单。我将以我的状态在数组中存储数据。我的Reactjs 动态生成的表单跟踪更改,但返回未定义的,reactjs,react-redux,Reactjs,React Redux,我使用一个类来动态生成一个由文本输入组成的表单。我将以我的状态在数组中存储数据。我的handleInputChange函数正在跟踪数据,但在我的handleInputChange方法的list[index][name]=value部分失败。错误是无法设置未定义的属性playerName。有人能帮我解释一下如何让它工作吗 import React, { Component } from "react"; class Form extends Component { con
handleInputChange
函数正在跟踪数据,但在我的handleInputChange方法的list[index][name]=value部分失败。错误是无法设置未定义的属性playerName
。有人能帮我解释一下如何让它工作吗
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;
import React,{Component}来自“React”;
类形式扩展组件{
建造师(道具){
超级(道具);
此.state={
玩家名称:[],
};
this.handleInputChange=this.handleInputChange.bind(this);
}
handleInputChange=(e,索引)=>{
const{playerNames}=this.state;
常量{name,value}=e.target;
const list=[…playerNames];
列表[索引][名称]=值;
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;
设倍数=[];
对于(var i=0;i(
this.handleInputChange(e,index)}
/>
))}
提交
);
}
}
导出默认表单;
失败,因为数组中没有初始对象
假设你想让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 });
const list = [...playerNames];
list[index] = {[name]:value};
this.setState({ playerNames: list });