Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  118] [ 4]  / answers: 1 / hits: 17381  / 8 Years ago, mon, january 16, 2017, 12:00:00

In components, I've seen different way of doing callbacks. What is the difference between:



<MyButton onPress={ () => {doSomething(data)} }>


and



<MyButton onPress={ this.doSomething.bind(this) }>

More From » reactjs

 Answers
3

<MyButton onPress={ () => {doSomething(data)} }>




This code block uses the ES6 Arrow function; which is another way of declaring a function in javascript. Also, the scope of this in arrow function depend where the function was created as opposed to normal scoping rule of this which by default depends on how the function was called.




<MyButton onPress={ this.doSomething.bind(this) }>




This statement makes a call to doSomething method. But since the event registration is done on different element, the Scope of doSomething is different and is forcefully binded by using bind method in javascript.



Also, in the second method you are not passing the data parameter, which you can pass using the second argument to the method like shown below.



<MyButton onPress={ this.doSomething.bind(this, data)} }>


[#59340] Friday, January 13, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Mar 17, 20, 00:00, 4 Years ago
;