0

I feel doing unnecessary routine, when I bind variables

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

or declare that = this in order to use current object in an async handler.

Is there a way to handle this routine in a prototype?

polina-c
  • 6,245
  • 5
  • 25
  • 36

3 Answers3

3

I'm very new to React, however, I know that using arrow functions simplifies this work:

import React from 'react';

class Input extends React.Component {

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

this way you don't need to bind the method in the constructor.

See more in this discussion: Can you bind arrow functions?

polina-c
  • 6,245
  • 5
  • 25
  • 36
1

As an alternative to the fine answer that PolinaC gave, you could use a proxy:

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];
            }
        });
    }
}
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Yes. You can derive your class or component from AdvancedComponent:

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 will make this available in every method even in the context of other object.

polina-c
  • 6,245
  • 5
  • 25
  • 36
  • Just curious. Why do you need a static method? Can you just not do in your `AdvancedComponent` constructor the following code `this.BindDirectPrototypeMethods()`? And in the Bind method do `Object.getPrototypeOf(this)`? – yaswanth Jul 27 '18 at 21:08