簡體   English   中英

單擊拖動和 onClick 反應?

[英]Click drag and onClick in react?

我正在建一張桌子。 當用戶單擊並拖動單元格時,它們之間的單元格會高亮顯示。 但我不知道為什么當我單擊單個單元格時,它還會在我單擊的最后一個單元格和新單元格之間突出顯示。 我想當我 onClick 它只在一個單元格上突出顯示

這是我的代碼:

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

export default function Table() {
    let div = [];
    const [start, setStart] = useState(null);
    const [end, setEnd] = useState(null);
    const [selecting, setSelecting] = useState(false);

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

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

    };
    let updateSelection = i => {
        if(selecting) {
            setEnd(i);
        }
    };
    for(let i = 0; i <= 31; i++ ) {
        let a = (

                <span
                    key={i}
                    className={
                        ((end != null  && start != null) && (end <= i && i<= start || (start <= i && i <= end)) ? "selected": "")
                    }
                    onMouseDown={()=>beginSelection(i)}
                    onMouseUp={()=>endSelection(i)}
                    onMouseMove={()=>updateSelection(i)}
                >
                {i}
            </span>
        );
        div.push(a);
    }
    return div;
}

這是我的完整代碼和演示: https : //codesandbox.io/s/github/Kalipts/table_grid請幫助我。 謝謝

我沒有對此進行測試,因為我無法讓您的鏈接正常工作,但我猜這是因為您正在經歷“異步狀態更改”。 來自文檔: 狀態更新可能是異步的

在您的beginSelection您正在調用updateSelection ,但我猜該代碼運行時選擇狀態實際上尚未更新。 一個簡單的解決方法是向您的 updateSelection 添加第二個參數

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

然后從beginSelectionendSelection調用updateSelection(i, true) ,而不是onMouseMove調用。 如果更容易,您也可以直接從beginSelectionendSelection調用setEnd 兩種選擇都應該有效,這或多或少是偏好問題。

問題是你設置 start onMouseDown 並只更新它 onMouseMove。 因此,您可以通過在 onMouseDown 事件中重置開始和結束來解決您的問題:

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

https://codesandbox.io/s/epic-newton-nlmvj

暫無
暫無

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

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