There's more...

Did you notice that we have been using the bind very often? When a method is passed as a prop to a child component, it loses the context of this, so binding to the context is necessary. Take the following example:

class Example { 
    fn() { return this } 
} 
const examp = new Example() 
const props = examp.fn 
const bound = examp.fn.bind(examp) 
console.log('1:', typeof examp.fn()) 
console.log('2:', typeof props()) 
console.log('3:', typeof bound()) 

The output displayed will be:

1: object 
2: undefined 
3: object 

Even though the constant props has a reference to the fn method of the examp instance of the Example class, it loses the context of this. That's why binding allows you to keep the original context. In React, we bind a method to the original context of this to be able to use our own instance methods, such as setState, when passing the function down to child components. Otherwise, the context of this will be undefined and the function will fail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.51.191