Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native 'this' references dedicatedWorkerGlobalScope instead of class instance

I have a component that I want to capture gesture events for using panResponder, however while trying to debug remotely (within chome) the 'this' context is referencing an instance of DedicatedWorkerGlobalScope instead of the class instance.

Say I have a simple component

import React, { Component } from 'react';

import {
    View,
    Text
    PanResponder
} from 'react-native';


class MyC extends Component
{
    constructor(props)
    {
      super(props);
      this.panResponder = PanResponder.create({

            onStartShouldSetPanResponder : () => true,
            onMoveShouldSetPanResponder : () => true,
            onPanResponderGrant : this.panResponderGranted ,
      })
    }

    panResponderGranted = (e, gestureState) => {

       this.setState({offset : gestureState.dx}); //this.setState is undefined
    }

    render(){

      return (<View />)
    }

}

now whenever I step through the panResponderGranted function and I look at the first level closure, I can see that there is a variable named _this that has the correct reference to the instance of the class. I am debugging wrong? is this expected behavior, or a bug?

like image 625
naughty boy Avatar asked Dec 05 '25 03:12

naughty boy


1 Answers

You need to bind panResponderGranted, because ES6 doesn't automatically bind functions.

I.e.

onPanResponderGrant : this.panResponderGranted.bind(this),
like image 111
Michael Helvey Avatar answered Dec 07 '25 17:12

Michael Helvey



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!