首页 > 解决方案 > 如何用鼠标选择范围单元格?

问题描述

我正在用 reactjs 建一个表。所以我想当用户单击一个单元格并按住移动到另一个单元格时。之间的单元格必须突出显示。我用 DOM 选择器来做。而且我认为这不是正确的反应方式。那么我如何在没有 DOM SELECTOR 的情况下做到这一点

这是我的 dom 选择代码:

import React, {useState} from "react";
import './Style.css';

export default function Table() {
    const [cell, setCell] = useState([]);
    let div = [];

    let selecting, start, end;

    let beginSelection = i => {
        selecting = true;
        start = i;
        updateSelection(i);
    };

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

    let updateSelection = i => {
        if (selecting)
            end = i;
        [...document.querySelectorAll('span')].forEach((span, i) =>
            span.classList.toggle('selected', i >= start && i <= end || i >= end && i <= start));
    };



    for(let i = 0; i < 31; i++) {
        let a = <span key={i} onMouseDown={()=>beginSelection(i)} onMouseUp={()=>endSelection(i)} onMouseMove={()=>updateSelection(i)}>{i}</span>;

        div.push(a);
        cell.push(a);
    }


    return div;
}

这是我的演示:https ://codesandbox.io/s/github/Kalipts/hover 请帮忙。谢谢

标签: javascriptreactjsreact-hooks

解决方案


using state & className for cell element

className={ (end <= i && i <= start) || (start <= i && i <= end) ? "selected" : "" }

https://codesandbox.io/s/ecstatic-driscoll-r8649


推荐阅读