我有一个html表,其中每一行都有react-select元素和按钮来删除同一行。我传递所选行索引并尝试删除同一行。当删除最后一行,它的工作正常,但是当我点击任何顶部行的例子与值“test1”在下面的图片中给出,其删除最后一行与选择值为“test 4”,我已经通过了索引值正确仍然其删除最后一行。
import { useEffect, useState } from "react";
import Select from "react-select";
function App(props) {
//const options = compliments;
const [state, setState] = useState({
rows: [
{
config: ""
}
]
});
const [configOpts, setConfigOpts] = useState([]);
const handleAddRow = () => {
const newRow = {
config: ""
};
setState({
...state,
rows: [...state.rows, newRow]
});
};
const handleRemoveRow = (idx) => () => {
const rows = [...state.rows];
rows.splice(idx, 1);
setState({
...state,
rows
});
};
const handleConfigChange = (index) => (selectedOption) => {
console.log("SelectedOption: " + selectedOption.label);
const rows = [...state.rows];
rows[index] = {
...rows[index],
["config"]: selectedOption.label
};
setState({
...state,
rows
});
};
useEffect(() => {
setConfigOpts([
{ label: "Test1", value: "Test1" },
{ label: "Test2", value: "Test2" },
{ label: "Test3", value: "Test3" },
{ label: "Test4", value: "Test4" }
]);
}, []);
return (
<>
<table>
{state.rows.map((item, idx) => (
<tr key={idx}>
<td>
<Select options={configOpts} onChange={handleConfigChange(idx)} />
</td>
<td>
<button onClick={handleRemoveRow(idx)}>Remove</button>
</td>
</tr>
))}
</table>
<div>
<button onClick={handleAddRow}>Add</button>
</div>
</>
);
}
export default App;
1条答案
按热度按时间pengsaosao1#
下面的代码按预期执行,没有任何问题。
在下面更新的代码中,每一行都有一个唯一的id,通过递增
id variable
生成。handleRemoveRow
函数现在根据id过滤行数组。