首页 > 解决方案 > 优化 reactjs 中的拖动单元格表?

问题描述

我正在建一张桌子。当用户单击一个单元格并拖过其他单元格时。之间的单元格必须突出显示。但是在我的实际项目中有 1000 个单元格,它太慢了,无论如何都要优化我的代码。

编码


export default function Table() {

    const [start, setStart] = useState(null);
    const [end, setEnd] = useState(0);
    const [selecting, setSelecting] = useState(false);
    const [isOpen, setIsOpen] = useState(false);

    let toggleModal = () => {
        setIsOpen(!isOpen);
    };

    let beginSelection = i => {
        setSelecting(true);
        setStart(i);
        setEnd(i);
        updateSelection(i);
    };

    let endSelection = (i = end) => {
        setSelecting(false);
        updateSelection(i);
    };

    let updateSelection = i => {
        if(selecting) {
            setEnd(i);
        }
    };

    let cells = [];
        for(let j = 0; j < 12*4; j++) {
            cells.push(
                <Cell key={j}
                      inputColor={
                          (end <= j && j <= start || (start <= j && j <= end) ? "#adf": "")
                      }
                      onMouseDown={()=>beginSelection(j)}
                      onMouseUp={()=>endSelection(j)}
                      onMouseMove={()=> updateSelection(j)}

                >
                    {j+1}
                </Cell>
            )
        }

    return (
        <TableCalendar>
            {cells}
        </TableCalendar>
    )
}

这是我的完整代码和演示:https ://codesandbox.io/s/elastic-noether-4krei

谢谢!

标签: reactjs

解决方案


推荐阅读