Avoid .bind in ES6 (7?) With Babel

I have this in my JSX:

<Options options={options} onOptionSelect={this.onOptionSelect.bind(this)} /> 

However, I swear I saw some quirkiness to deny the need for .bind when passing callback methods to React child components, am I correct?

+5
source share
2 answers

You can use the arrow function in combination with property initialization.

 class Component extends React.Component { handleClick = () => { console.log(this.props); } render() { return <div onClick={this.handleClick} /> } } 

Since the arrow function is declared in the constructor area, but because the arrow functions support this from their declaration area, it all works. The disadvantage here is that they will not be functions on the prototype, they will all be recreated with each component. However, this is not so much, since bind does the same.

+5
source

You can bind all the functions of a component using the syntax of the ES2015 class using this helper function autoBind :

 class Component extends React.Component { constructor(props) { super(props); autoBind(this); } onOptionSelect() { // do stuff } render() { return <Options options={options} onOptionSelect={this.onOptionSelect} />; } } function autoBind(obj) { getAllMethods(obj.constructor.prototype) .forEach(mtd => { obj[mtd] = obj[mtd].bind(obj); }); } function getAllMethods(obj) { return Object.getOwnPropertyNames(obj).filter(key => typeof obj[key] == "function"); } 

Note that Component does not need to use methods defined using arrow functions.

0
source

Source: https://habr.com/ru/post/1237274/


All Articles