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?
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?
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?
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];
}
});
}
}
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.