繁体   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