簡體   English   中英

在 React 中刪除和復制數組元素

[英]Deleting and copying array elements in React

我的任務是在我們的一張桌子上添加一個復制和刪除按鈕。 我正在嘗試將索引從地圖傳遞到刪除並復制 onclick,這確實刪除了但是...

問題:如果您復制一行,它將具有與原始行完全相同的“i”,並且它會移動其下方所有行的位置,從而極大地破壞了刪除

我的印象是,如果我將 setRows() 設置為新的東西,它會再次運行映射並在每個函數中為它們提供所有正確的 i,但情況似乎並非如此,為什么?

const AdvancedTable = () => {
    const [rows, setRows] = useState(tableRows); ///tableRows is basically an array of divs
    const deleteOnClick = (i: number) => {
        setRows(() => {
            const myRows = [...rows];
            myRows.splice(i, 1);
            return myRows;
        });
    }
    const copyOnClick = (i: number) => {
        setRows(() => {
            const myRows = [...rows];
            myRows.splice(i, 0, rows[i]);
            return myRows;
        });
    }
    return (

            <Paper>
                     {
                         rows.map((row: any, i: number) => (
                                     <div>
                                         <IconButton onClick={() => { deleteOnClick(i) }} size="small">
                                             <ClearIcon />
                                         </IconButton>
                                         <IconButton onClick={() => { copyOnClick(i) }} size="small">
                                             <FileCopyIcon />
                                         </IconButton>
                                     </div>
                                 </TableCell>
                                 {row}

                         ))}
            </Paper>
    );
}
export default AdvancedTable;

您是否希望復制方法復制您單擊的行下方的行或將其發送到數組的末尾?

也許這可以幫助您假設您可以使用 .i 從行對象中調用 i 值

const copyOnClick = (i: number) => {
    setRows(() => {
        const myRows = [...rows];
        // send the new row to the end of the array
        myRows.splice(rows.length, 0, rows[i]);
        // change the new row i value to + 1 of the last object that was previously in the array
        myRows[myRows.pop().i].i = rows.pop().i + 1
        return myRows;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM