【问题标题】:Getting the event object with Underscore debounce[React]使用 Underscore debounce [React] 获取事件对象
【发布时间】:2017-06-29 16:45:51
【问题描述】:

我正在尝试对我设法做到的操作使用 debounce,但是我想将 e 作为参数传递,但它不起作用。有什么办法可以做到吗?

 constructor(props, context) {
    super(props, context);
    this.testing = _.debounce(this.testing.bind(this), 2000);
}

 @action testing(e) {
     alert("debounced!!");
     //use e.target ... 
   }

如果我拿走 e 它将进入函数,否则不会。我应该怎么做才能解决这个问题?

【问题讨论】:

    标签: reactjs debounce


    【解决方案1】:

    您可以使用 event.persist() 将事件传递给 debounce 方法。

    根据 DOCS:

    如果你想以asynchronous 的方式访问事件属性,你 应该在事件上调用event.persist(),这将删除 池中的合成事件,并允许对该事件的引用 由用户代码保留。

    所以你可以把事件当作

    constructor(props, context) {
        super(props, context);
        this.testing = _.debounce(this.testing.bind(this), 2000);
    }
    
     @action testing(e) {
         alert("debounced!!");
         //use e.target ... 
       }
    onChange = (e) => {
        e.persist();
        this.testing(e);
    }
    

    【讨论】:

    【解决方案2】:

    分配this.testing后,

    this.testing = _.debounce(this.testing.bind(this), 2000);

    在某些情况下,您应该使用参数调用该方法

    onSumbit(e){
        this.testing(e);
    }
    

    类似的东西

    【讨论】:

    • 我又试了一次,当它到达 this.testing(e) 的代码点时,它说 this.testing 不是一个函数。
    • this.testing = _.debounce(this.testing.bind(this), 2000);替换成this.debounceTesting = _.debounce(this.testing.bind(this), 2000);,用this.debounceTesting(e)代替this.testing(e),引用指针和方法应该有不同的名字。
    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 2016-08-01
    • 2020-09-05
    • 2017-05-05
    • 2021-04-08
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多