You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何避免双击video元素时触发单击事件?

React Video元素区分单击与双击事件的解决方案

问题核心是浏览器的事件触发机制:双击事件(dblclick)触发前,会先触发两次单击事件(click),直接绑定两个事件会导致双击时单击函数也被执行。解决思路是通过延迟判断,在单击后等待一段时间,若这段时间内未触发双击则执行单击逻辑,否则取消单击逻辑。

具体实现步骤

  1. 在组件中声明状态存储定时器ID,用于后续清除定时器:
const [clickTimeoutId, setClickTimeoutId] = useState(null);
  1. 修改单击处理函数,添加延迟执行逻辑:
const videoFunction = (event, index) => {
  // 清除之前可能存在的定时器,避免重复触发
  if (clickTimeoutId) clearTimeout(clickTimeoutId);
  
  // 设置300ms延迟,若300ms内未触发双击则执行单击逻辑
  const timeoutId = setTimeout(() => {
    // 这里放入你原本的单击逻辑
    console.log('执行单击操作', index);
  }, 300);
  
  setClickTimeoutId(timeoutId);
};
  1. 修改双击处理函数,先清除单击定时器,再执行双击逻辑:
const handleDoubleClick = (event, index) => {
  // 清除单击定时器,阻止单击逻辑执行
  if (clickTimeoutId) clearTimeout(clickTimeoutId);
  
  // 这里放入你原本的双击逻辑
  console.log('执行双击操作', index);
};
  1. 组件卸载时清除定时器,避免内存泄漏:
useEffect(() => {
  return () => {
    if (clickTimeoutId) clearTimeout(clickTimeoutId);
  };
}, [clickTimeoutId]);

修改后的Video组件代码

<video
  id={`post${index}`}
  width="640"
  height="360"
  onDoubleClick={(event) => handleDoubleClick(event, index)}
  className="post__media_video"
  alt="Post Content"
  style={{
    objectFit: "contain",
    background: "black",
  }}
  onClick={(event) => videoFunction(event, index)}
>
  <source src={item.image} type="video/mp4" />
  <source src={item.image} type="video/webm" />
  Your browser does not support the video tag.
</video>

注意事项

  • 延迟时间(300ms)可根据需求调整,200-300ms是符合多数用户双击习惯的区间。
  • 双击触发时必须清除单击定时器,否则单击逻辑仍会执行。
  • 组件卸载时清除定时器,防止内存泄漏问题。

内容的提问来源于stack exchange,提问作者Abhinand Tk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:41:08