antd table的单击事件和双击事件冲突

发布时间:2024年01月22日

问题:当table上同时有onClick和onDoubleClick时,双击会一直触发单击事件。

解决方法:使用延迟定时器-setTimeout

??????????????????单击事件延迟执行,如果检测到连续点击,则是双击事件,不再执行单击事件。

代码实现:

import React, { useState } from "react";
import { Table } from "antd";
import { ColumnsType } from "antd/lib/table";

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
}

const MyTable: React.FC = () => {
  const [clickTimeout, setClickTimeout] = useState<NodeJS.Timeout | null>(null);

  const handleSingleClick = (e: React.MouseEvent<HTMLElement, MouseEvent>, record: T) => {
    if (clickTimeout) {
      clearTimeout(clickTimeout);
      setClickTimeout(null);
      console.log("Double click");
    } else {
      setClickTimeout(
        setTimeout(() => {
          console.log("Single Click");
          // 在这里执行单击事件的处理逻辑
          setClickTimeout(null);
        }, 300)
      );
    }
  };

  const handleDoubleClick = (e: React.MouseEvent<HTMLElement, MouseEvent>, record: T) => {
    clearTimeout(clickTimeout as NodeJS.Timeout);
    setClickTimeout(null);
    console.log("Double click");
    // 在这里执行双击事件的处理逻辑
  };

  const data: DataType[] = [
    {
      key: "1",
      name: "xiaohong",
      age: 18,
      address: "xxxxxx",
    },
    {
      key: "2",
      name: "xiaoming",
      age: 10,
      address: "xxxxxxx",
    },
  ];

  const columns: ColumnsType<DataType> = [ 
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age",
    },
    {
      title: "Address",
      dataIndex: "address",
      key: "address",
    },
  ];

  return (
    <Table<DataType>
      dataSource={data}
      columns={columns}
      onRow={(record) => {
        return {
          onClick: (e) => handleSingleClick(e, record);,
          onDoubleClick: (e) => handleDoubleClick(e, record),
        };
      }}
    />
  );
};

export default MyTable;

文章来源:https://blog.csdn.net/qq_48691693/article/details/135752240
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。