Lodash通过React输入进行反跳 [英] Lodash debounce with React Input

查看:60
本文介绍了Lodash通过React输入进行反跳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将lodash的反跳功能添加到从输入onChange事件调用的搜索功能中.下面的代码生成类型错误期望功能",据我了解,因为lodash需要功能.什么是正确的方法,可以全部内联完成吗?到目前为止,我已经尝试了几乎所有关于SO的示例,但均无济于事.

I'm trying to add debouncing with lodash to a search function, called from an input onChange event. The code below generates a type error 'function is expected', which I understand because lodash is expecting a function. What is the right way to do this and can it be done all inline? I have tried nearly every example thus far on SO to no avail.

search(e){
 let str = e.target.value;
 debounce(this.props.relay.setVariables({ query: str }), 500);
},

推荐答案

去抖动功能可以在JSX中内联传递,也可以直接设置为类方法,如下所示:

The debounce function can be passed inline in the JSX or set directly as a class method as seen here:

search: _.debounce(function(e) {
  console.log('Debounced Event:', e);
}, 1000)

提琴手: https://jsfiddle.net/woodenconsulting/69z2wepo/36453/

如果您使用的是es2015 +,则可以直接在 constructor 中或在诸如 componentWillMount 之类的生命周期方法中定义反跳方法.

If you're using es2015+ you can define your debounce method directly, in your constructor or in a lifecycle method like componentWillMount.

示例:

class DebounceSamples extends React.Component {
  constructor(props) {
    super(props);

    // Method defined in constructor, alternatively could be in another lifecycle method
    // like componentWillMount
    this.search = _.debounce(e => {
      console.log('Debounced Event:', e);
    }, 1000);
  }

  // Define the method directly in your class
  search = _.debounce((e) => {
    console.log('Debounced Event:', e);
  }, 1000)
}

这篇关于Lodash通过React输入进行反跳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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