使用 Underscore debounce[React] 获取事件对象

IT技术 reactjs debounce
2021-04-30 03:42:01

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

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

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

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

2个回答

您可以使用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);
}

赋值后this.testing

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

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

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

像这样的东西