如何停止绑定每个处理程序并声明变量 'that'

How to stop binding every handler and declaring variable 'that'

当我绑定变量时,我觉得在做不必要的例程

this.handleInputChange = this.handleInputChange.bind(this);

或声明 that = this 以便在异步处理程序中使用当前对象。

有没有办法在原型中处理这个例程?

是的。您可以从 AdvancedComponent:

派生您的 class 或组件
import { Component } from 'react';

class AdvancedComponent extends Component {

    constructor(props) {
        super(props);

        AdvancedComponent.BindDirectPrototypeMethods(this);
    }    

    static BindDirectPrototypeMethods(obj) {
        const prot = Object.getPrototypeOf(obj);
        const methods = Object.getOwnPropertyNames(prot).filter(m => {
            return typeof prot[m] === 'function' && m !== 'constructor';
        });

        methods.forEach( m => {
            obj[m] = obj[m].bind(obj);
        })
    }
}

export default AdvancedComponent;

这将使 this 在每个方法中可用,即使在其他对象的上下文中也是如此。

作为 PolinaC 给出的良好答案的替代方案,您可以使用代理:

class MyClass extends Component {
    constructor(props) {
        super(props);
        return new Proxy(this, {
            get(obj, prop) {
                return typeof obj[prop] === 'function' ? obj[prop].bind(obj) : obj[prop];
            }
        });
    }
}

我是 React 的新手,但是,我知道使用箭头函数可以简化这项工作:

import React from 'react';

class Input extends React.Component {

 handleInputChange = () => {
  // do something 
}
 render() {
   return(
     <div>
       <input onChange={this.handleInputChange} />
     </div>  
   )
 }

这样就不需要在构造函数中绑定方法了。

在此讨论中查看更多内容: