延迟React onMouseOver事件 [英] Delay React onMouseOver event

查看:98
本文介绍了延迟React onMouseOver事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素列表,将鼠标悬停在其中之一时,我想更改状态.

I have a list of elements, when hovering one of these, I'd like to change my state.

<ListElement onMouseOver={() => this.setState({data})}>Data</ListElement>

不幸的是,如果我将鼠标移到列表上,我的状态会快速连续改变几次.我想延迟状态更改,以使其等待半秒钟才被解雇.有办法吗?

Unfortunately, if I move my mouse over the list, my state changes several times in a quick succession. I'd like to delay the change on state, so that it waits like half a second before being fired. Is there a way to do so?

推荐答案

您可以使用 去抖动 作为专用软件包,或从 lodash 等获取它:

You can use debounce as a dedicated package or get it from lodash, etc:

对于执行仅应在重复操作完成后才发生的行为有用.

Useful for implementing behavior that should only happen after a repeated action has completed.

const debounce = require('debounce');

class YourComponent extends Component {
  constructor(props) {
    super(props);

    this.debouncedMouseOver = debounce(handleMouseOver, 200);
  }

  handleMouseOver = data => this.setState({ data });

  render() {
    const data = [];
    return <ListElement onMouseOver={() => this.debouncedMouseOver(data)}>Data</ListElement>;
  }
}

这篇关于延迟React onMouseOver事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆