Skip to content Skip to sidebar Skip to footer

Bind In Constructor Or Fat Arrow In Class

So i'm wondering if there is a difference between this: import React, { Component, PropTypes } from 'react'; class Example extends Component { constructor(props) { super(pro

Solution 1:

The best place to bind your event handlers is your constructor. This way your event handler has its context bound to the component instance.You can access props and state and call setState or forceUpdate from such bound handler.

Binding with arrow functions have their own advantages as well. Arrow functions always gets the context from where they have been defined. So in fact, this example is equivalent to:

The arrow function syntax is a way of defining function with a syntax like this:

change = (ev) => this.setState({ text: ev.target.value });

It is a more concise way than writing a function(ev) { .... } statement. If you don’t provide { and } brackets after the => arrow, such function is a single expression which is returned instantly. So this desugars to something like:

change = function(ev) { return this.setState({ text: ev.target.value }); }.bind(this);

And hence both of .bind() and arrow function cause a new function to be created

Concluding, the way you want to bind your function depends on your use case.

For more details you can read up this article:


Post a Comment for "Bind In Constructor Or Fat Arrow In Class"