Binding in the Constructor

Recall that we need to bind the correct context to event handlers when we use ES6 class syntax.(In earlier ES implementations `this` is automatically bound to the event handler.)



For example, if we left our implementation without the bind we would not have access to any of the SlideControls props, and `this` would refer to the Button, not the SlideControls.



Another way to bind the context is to use arrow functions.

Two Binding Methods:





Although we can simply add bind to every function that needs a reference to the element it was called from, it's not good practice.
This makes the code look pretty messy and long when you have many elements.

React "recommends that you bind your event handlers in the constructor so they are only bound once for every instance." (React Reference Doc)

Example of Binding in the Constructor:



All you're really doing is setting this.previousSlide to its bound version, creating a shorthand. So go on! Bind in your constructor.

Comments

Popular Posts