我已经费尽心思搜索答案,但我需要一些人类的帮助。
我有一个简单的表单,用户可以添加额外的字段。用户还可以删除不再相关的字段。
问题出在删除字段上。
这些字段是从组件状态中的数组呈现出来的,但当我尝试从数组中删除一个项目时,总是删除最后一个项目。
import React, { Component } from "react";
class Form_newPriority extends Component {
constructor(props) {
super(props);
this.state = {
listName: "",
rows: [{ id: 1, fieldValue: "" }],
};
}
addrow = () => {
const rows = [...this.state.rows];
rows.push({
id: rows.length + 1,
fieldValue: "",
});
this.setState({ rows: rows });
};
removeRow = (idx) => {
const rows = [...this.state.rows];
rows.splice(idx, 1);
this.setState({ rows: rows });
};
render() {
return (
<div>
<input
className="w-full bg-white border border-alice px-4 py-2 mb-1 h-12 rounded-lg"
type="text"
></input>
<h2>Items:</h2>
{this.state.rows.map((row, idx) => {
return (
<React.Fragment>
<input
className="w-half bg-white border border-alice px-4 py-2 mb-4 mr-4 h-12 rounded-lg"
key={idx}
type="text"
placeholder={idx}
></input>
<button
className="mb-4 text-red-700 inline-block"
onClick={() => {
this.removeRow(idx);
}}
>
Remove
</button>
</React.Fragment>
);
})}
<button
className="bg-alice hover:bg-gray-400 text-c_base text-sm font-bold py-1 px-2 rounded block mr-4"
onClick={this.addrow}
>
Add row
</button>
</div>
);
}
}
export default Form_newPriority;
我也尝试过
rows.filter()
但是这会产生相同的结果。
我对JS和React都比较新,所以我在这里做了一些愚蠢的事情吗?
key
属性。 - ROOT