React 总是在使用 react-select 元素删除顶行时删除最后一行

问题描述 投票:0回答:0

我有一个 html 表,其中每一行都有 react-select 元素和按钮来删除同一行。我传递选定的行索引并尝试删除同一行。删除最后一行时,它工作正常但是当我单击下图中给出的值为“test1”的任何顶行示例时,它删除了选择值为“test4”的最后一行,我已经正确传递了索引值仍然删除最后一行。

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;

代码沙盒

javascript reactjs react-native react-hooks react-select
© www.soinside.com 2019 - 2024. All rights reserved.