问题:当table上同时有onClick和onDoubleClick时,双击会一直触发单击事件。
解决方法:使用延迟定时器-setTimeout
单击事件延迟执行,如果检测到连续点击,则是双击事件,不再执行单击事件。文章来源:https://www.toymoban.com/news/detail-822370.html
代码实现:文章来源地址https://www.toymoban.com/news/detail-822370.html
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;
到了这里,关于antd table的单击事件和双击事件冲突的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!