Javascript 检查延迟后元件是否仍有鼠标指针

Javascript 检查延迟后元件是否仍有鼠标指针,javascript,reactjs,mouseevent,Javascript,Reactjs,Mouseevent,我用mouseenter和mouseleave <button onMouseEnter={this.MouseEnter}>hover</button> MouseEnter(e) { setTimeout(() => { //check if mouse over still on this element // do action }, 600); } 悬停 穆塞纳(e){ 设置超时(()=>{ //检查鼠

我用
mouseenter
mouseleave

<button onMouseEnter={this.MouseEnter}>hover</button>

MouseEnter(e) {
    setTimeout(() => {
        //check if mouse over still on this element 
        // do action
    }, 600);
}
悬停
穆塞纳(e){
设置超时(()=>{
//检查鼠标是否仍停留在此元素上
//行动
}, 600);
}
问题是,当我快速移动块时,最后一个块在超时之前检测到鼠标指针并执行操作,即使我没有在块上悬停(这是一个错误),我想使其仅在块上悬停
500ms
后运行操作

p、 s:我正在使用react.js

如果触发了
mouseLeave
事件,您真正缺少的是超时回调的无效性。为此,您需要保留返回的
setTimeout
值,以便在计时器过期之前调用
cleartimout
(或者如果组件卸载!!)

以下是基于类的组件中的基本机制:

state = {
  hovered: false
};
timer;

mouseEnterHandler = () => this.setState({ hovered: true });
mouseLeaveHandler = () => this.setState({ hovered: false });

onTimeout = () => {
  // Do action
};

clearTimer = () => {
  clearTimeout(this.timer);
};

// Here's the meat:
// If state updates, then componentDidUpdate is called,
// if the new hovered state is true, set timeout and save the
// returned reference, else clear the timeout using the saved
// timer reference.

componentDidUpdate() {
  const { hovered } = this.state;

  if (hovered) {
    this.timer = setTimeout(this.onTimeout, 500);
  } else {
    this.clearTimer();
  }
}

// This is component cleanup, if the component unmounts before
// the timer expires you may not want the "Do action" to fire,
// so we go ahead and clear the timeout so you're not accidentally
// accessing state/props of an unmounted component.

componentWillUnmount() {
  this.clearTimer();
}
以下为等效功能部件逻辑:

const [hovered, sethovered] = useState(false);

const mouseEnterHandler = () => sethovered(true);
const mouseLeaveHandler = () => sethovered(false);

const onTimeout = () => {
  // Do action
};

useEffect(() => {
  const timer = hovered && setTimeout(onTimeout, 500);
  return () => {
    clearTimeout(timer);
  };
}, [hovered]);

非常感谢!这消除了我正在做的工作中的许多模糊。最后一件事
定时器
我应该把它设置为
this.timer
构造函数(道具)
中?我这样做了,但是触发了一个错误,终端
期望一个赋值或函数调用,相反看到了一个expression
@SaidBenmoumen如果在
构造函数中设置了
那么你应该提供一个初始值,
this.timer=null。更新了我的代码沙盒演示。