Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native component callback functions

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) }>
like image 992
Gundam Meister Avatar asked Oct 24 '25 03:10

Gundam Meister


1 Answers

<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)} }>

like image 53
Abhinav Galodha Avatar answered Oct 26 '25 16:10

Abhinav Galodha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!