代码之家  ›  专栏  ›  技术社区  ›  polina-c

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

  •  0
  • polina-c  · 技术社区  · 8 年前

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

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

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

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

    3 回复  |  直到 8 年前
        1
  •  3
  •   polina-c    8 年前

    import React from 'react';
    
    class Input extends React.Component {
    
     handleInputChange = () => {
      // do something 
    }
     render() {
       return(
         <div>
           <input onChange={this.handleInputChange} />
         </div>  
       )
     }
    

    Can you bind arrow functions?

        2
  •  1
  •   trincot    8 年前

    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];
                }
            });
        }
    }
    
        3
  •  0
  •   polina-c    8 年前

    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