【问题标题】:(react) debounce with arguments(反应)用参数去抖动
【发布时间】:2016-03-08 16:30:24
【问题描述】:

我正在尝试去抖动作为道具传递给组件的函数(使用下划线的去抖动)。我过去可以通过以下方式做到这一点:

  componentWillMount() {
    this.handleInputTextChangeDebounced = debounce(() => {
      console.log('I debounce!');
    }, 250);
  },

这很好用,但现在我需要从触发 handleInputTextChangeDebounced 的 onChange 访问事件参数(以便我可以从输入中获取值)

例如:

  <input onChange={this.handleInputTextChangeDebounced} data-option='buildNumber' />

我不能简单地使用 ref,因为我有许多表单输入选项要与这个去抖动函数一起使用。

我尝试将 debounce 作为一个函数返回到 handleInputTextChangeDebounced 中,该函数将接收事件,但这似乎阻止 debounce 工作。

建议?

【问题讨论】:

  • 什么是debounce?它是否将传递的参数转发给它的回调?
  • 我第二个@zerkms 评论。任何有用的去抖动都应该调用你的匿名函数来传递事件。
  • 对不起,我没有提到 - 我一直在使用下划线的 debounce underscorejs.org/#debounce
  • 如果我尝试使用 debounce debounce((e) =&gt; { 传递一些东西,我会得到合成事件对象,但所有属性都是空的

标签: javascript reactjs


【解决方案1】:

通过两个步骤找出解决方案。我调用了一个普通的类函数(handleInputTextChange),从输入字段中提取了值,然后我分别调用了去抖函数(handleInputTextChangeDebounced)。

handleInputTextChange(e) {
  this.handleInputTextChangeDebounced(e.target.value);
},

handleInputTextChangeDebounced: debounce((value) => {
  // do debounced stuff with value here...
}, 700),


<input onChange={this.handleInputTextChange} type='text' data-option='buildNumber' />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2021-08-19
    • 1970-01-01
    • 2017-04-27
    • 2020-03-27
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多