When I print this inside of onScroll handler I get DedicatedWorkerGlobalScope instead of Constructor.
var Frame = React.createClass({
_handleScroll: (ev) => {
console.log(this) //DedicatedWorkerGlobalScope
},
render: function() {
return (
<ScrollView
ref='scrollViewH'
onScroll={this._handleScroll}>
{items}
</ScrollView>
);
}
});
If I handle scroll with inline function this works correct:
var Frame = React.createClass({
render: function() {
return (
<ScrollView
ref='scrollViewH'
onScroll={(ev) => {
console.log(this) //Constructor
}}>
{items}
</ScrollView>
);
}
});
Binding this does not work.
onScroll={this._handleScroll.bind(this)}
When you use the arrow function declaration, you are using 'this' available at the same level as your variable 'Frame', because es6 is inferring the context. This is explained in the article below, which states
[Arrow functions] have implicit return and most importantly, they always use the value of this from the enclosing scope
The article gives a pretty decent explanation how binding syntax works in ES6 and how to get the expected behavior:
https://www.sitepoint.com/bind-javascripts-this-keyword-react/
When I rewrote callback declaration in old fashion way (without ES6 Arrow Functions) it works as expected. Why So?!!!! If some one knows, please give me an answer.
var Frame = React.createClass({
_handleScroll: function(ev) {
console.log(this); //Constructor
},
render: function() {
return (
<ScrollView
ref='scrollViewH'
onScroll={this._handleScroll}>
{items}
</ScrollView>
);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With