Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an anonymous function to onPanResponderMove

I have a javascript issue and I'm not sure how to resolve it.

In my React Native application, I have a panResponder and I'm using this hook to call Animated.event.

this.panResponder = PanResponder.create({
    /* ... some other methods ... */
    onPanResponderMove: Animated.event([null, { dx: this.state.x, dy: this.state.y }]),
});

Although, I would like the hook to be an anonymous function instead, to be able to do some other things. I tried a few different way to use an anonymous function instead but I can't make it to work.

this.panResponder = PanResponder.create({
    /* ... some other methods ... */
    onPanResponderMove: (event, gestureState) => {
        this.callSomething(); 
        return Animated.event([null, { /* I'm not sure what to pass here to map with gestureState... */ }]);
    },
});

I've read the documentation but even with that I still don't know.

Can you help me out?

Thanks.

Update:

I've finally did something like that:

let valueY;
this.panResponder = PanResponder.create({
    /* ... some other methods ... */
    onPanResponderGrant: () => {
        valueY = this.state.y._value;
    },
    onPanResponderMove: (event, gestureState) => {
        this.callSomething();
        let panY = valueY + gestureState.dy;
        this.state.y.setValue({ y: panY });
    },
});

I don't think that's the best way to do it though...

like image 251
alexmngn Avatar asked Apr 15 '16 02:04

alexmngn


2 Answers

The thing is that Animated.event(...) is actually returning a function so to immediately invoke it you have to do something like this:

this.panResponder = PanResponder.create({
  ...
  onPanResponderMove: (e, gestureState) => {
    // custom logic here
    ...

    Animated.event([null, {
      dx: this.state.pan.x,
      dy: this.state.pan.y,
    }])(e, gestureState); // <<--- INVOKING HERE!
  },
});
like image 109
patotoma Avatar answered Oct 14 '22 16:10

patotoma


In case this is useful to anyone, I've just had the same issue. I ended up with, roughly:

let mover = Animated.event([ null, { dy: this.state.pan.y }]) ;
let repsponder = PanResponder.create({
    ....
    onPanResponderMove: (e, gesture) => {
        this.doSomething() ;
        return mover(e, gesture) ;
        },
    }) ;

The important bit seems to be calling Animated.event outside the onPanResponderMove code. Note that in the examples that usually appear, the code is onPanResponderMove: Animated.event(...) so a single Animated.event thing gets created, but if you it inside the onPanResponderMove code (as in alexmngn's first attempt), a new thing (whatever it is!) gets created on every call of the onPanResponderMove code - which I'm guessing is the problem.

like image 25
Mike Richardson Avatar answered Oct 14 '22 18:10

Mike Richardson