为什么removeEventListener不适用于React安装的事件处理程序



我有一个React组件,它将把一堆li元素附加到DOM。其中一些对它们有一个点击Eventlistener。在用户单击那些特殊的li之后,我试图禁用eventlistener,为此我使用了event.currentTarget.removeEventListener('click', this.handleMouse),但它不起作用。以下是代码的相关部分:

var DisplayList = React.createClass({
  /* ... */
  
  handleMouse: function (event) {
    event.currentTarget.style.backgroundColor = 'white';
    this.props.changeCounts(-1); 
    event.currentTarget.removeEventListener('click', this.handleMouse); //NOT WORKING
  },
  /* ... */
  render: function () {
    var self = this;
    return(
      <div id = "listing-boxes-wrapper">
          {
            this.props.sortedList.map(function(item, index){
              if (self.state.changedHabit.indexOf(item.habitid) > -1) {
                return  <li key={index} style={{backgroundColor: '#ccc'}} className = "text-center" onClick={self.handleMouse}>{item.description} 
                        </li>
              }else{
                return  <li key={index} className =" text-center">{item.description}
                        </li>
              }
            })
          }
      </div>
    )
  }
});

reactjs使用Function.prototype.bind将上下文绑定到处理程序(否则this将为undefined)。

因此,引擎盖下发生的事情类似于:

element.addEventListener('click', this.handleMouse.bind(this));

因此,正如您所看到的,它是添加到侦听器的另一个函数,而不是this.handleMouse

因此,在那之后,你就无法移除它,因为它甚至都没有连接。

react方式的解决方案只是在没有处理程序的情况下再次重新呈现元素,以便react分离处理程序本身。

react中的相关(?)代码:

/**
 * Binds a method to the component.
 *
 * @param {object} component Component whose method is going to be bound.
 * @param {function} method Method to be bound.
 * @return {function} The bound method.
 */
function bindAutoBindMethod(component, method) {
  var boundMethod = method.bind(component);
  if (__DEV__) {
    // stripped as irrelevant
  }
  return boundMethod;
}
/**
 * Binds all auto-bound methods in a component.
 *
 * @param {object} component Component whose method is going to be bound.
 */
function bindAutoBindMethods(component) {
  var pairs = component.__reactAutoBindPairs;
  for (var i = 0; i < pairs.length; i += 2) {
    var autoBindKey = pairs[i];
    var method = pairs[i + 1];
    component[autoBindKey] = bindAutoBindMethod(
      component,
      method
    );
  }
}

最新更新