我已经四处寻找答案,但我只需要一些人工帮助。
我有一个简单的表单,用户可以在其中添加其他字段。用户还可以删除不再相关的字段。
这是我遇到问题的删除字段。
这些字段是从组件状态中的数组呈现的,但是当我尝试从数组中删除一个项目时,它始终是数组中最后一个被删除的项目。
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 还很陌生,所以我在这里做了一些愚蠢的事情吗?