亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查延遲后元素是否仍有 mouseenter

檢查延遲后元素是否仍有 mouseenter

RISEBY 2022-06-05 10:27:45
我用 amouseenter和mouseleave<button onMouseEnter={this.MouseEnter}>hover</button>MouseEnter(e) {    setTimeout(() => {        //check if mouse over still on this element         // do action    }, 600);}問題是當我快速移動塊時,最后一個塊在超時之前檢測到 mouseenter 并執行操作,即使我沒有懸停在塊上,這是一個錯誤,我想讓它只在500ms懸停后運行在塊上。ps:我正在使用 react.js
查看完整描述

1 回答

?
Helenr

TA貢獻1780條經驗 獲得超4個贊

如果事件被觸發,您真正缺少的是超時回調的失效。mouseLeave為此,您需要保留返回的setTimeout值以便clearTimeout在計時器到期之前調用(或者如果組件卸載?。。?/p>


以下是基于類的組件中的基本機制:


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]);


查看完整回答
反對 回復 2022-06-05
  • 1 回答
  • 0 關注
  • 79 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號