简体   繁体   English

React.js和反跳onChange事件不起作用

[英]React.js and debouncing onChange event is not working

I have implemented react component on change event like this: 我已经在更改事件上实现了react组件,如下所示:

NewItem = React.createClass({

  componentWillMount: function() {
    this._searchBoxHandler = debounce(this._searchBoxHandler, 500);
  },

  _searchBoxHandler: function(event) {
    this.context.flux.getActions('order').setOrders(...);
  },

  render: function () {
    ...
    var _self = this;
    return (<TextField onChange={_self._searchBoxHandler} />)      
  })

});

I've done this implemention by checking this answer (Good idea section): https://stackoverflow.com/a/28046731/842622 我已经通过检查以下答案(好主意部分)完成了此实现: https : //stackoverflow.com/a/28046731/842622

But it's not working. 但这不起作用。 I'm always having 'Cannot read property 'value' of null' from event object. 我总是从事件对象获得'无法读取null的属性'值'。

Am I missing something here? 我在这里想念什么吗?

You need to bind your context or use a closure to maintain scoping: 您需要绑定上下文或使用闭包来维护作用域:

 NewItem = React.createClass({ componentWillMount: function() { this._searchBoxHandler = debounce(this._searchBoxHandler.bind(this), 500); }, _searchBoxHandler: function(event) { this.context.flux.getActions('order').setOrders(...); }, render: function () { ... var _self = this; return (<TextField onChange={_self._searchBoxHandler} />) }) }); 

A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (eg by using that method in callback-based code). 对于新的JavaScript程序员来说,一个常见的错误是从对象中提取一个方法,然后再调用该函数并期望它使用原始对象作为其对象(例如,在基于回调的代码中使用该方法)。 Without special care however, the original object is usually lost. 但是,如果没有特别注意,通常会丢失原始对象。 Creating a bound function from the function, using the original object, neatly solves this problem.. - MDN 使用原始对象从函数创建绑定函数可以很好地解决此问题。-MDN

Some nice docs on binding and context: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind 关于绑定和上下文的一些不错的文档: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

or you could use a 'fat-arrow' function to access parent class scope: 或者您可以使用“ fat-arrow”函数来访问父类范围:

debounce((event) => { this._searchBoxHandler(event); }, 500);

Note: I wouldn't overwrite the declared function property in the componentWillMount invocation, instead you could store the debounced instance in another property like _debouncedSearchBoxHandler 注意:我不会在componentWillMount调用中覆盖声明的function属性,而是可以将已去抖动的实例存储在另一个属性中,例如_debouncedSearchBoxHandler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM