Home > Blockchain >  How to calculate and detect PanResponder event?
How to calculate and detect PanResponder event?

Time:11-25

I am pretty new to animation and gesture handler. I am reading the documentation in the official react native animations and I found a snippet of this code that lets you move around the blue box.

https://reactnative.dev/docs/animations

import React, { useRef } from "react";
import { Animated, View, StyleSheet, PanResponder, Text } from "react-native";

const App = () => {
  const pan = useRef(new Animated.ValueXY()).current;
  const panResponder = useRef(
    PanResponder.create({
      onMoveShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([
        null,
        { dx: pan.x, dy: pan.y }
      ]),
      onPanResponderRelease: () => {
        Animated.spring(pan, { toValue: { x: 0, y: 0 } }).start();
      }
    })
  ).current;

  return (
    <View style={styles.container}>
      <Text style={styles.titleText}>Drag & Release this box!</Text>
      <Animated.View
        style={{
          transform: [{ translateX: pan.x }, { translateY: pan.y }]
        }}
        {...panResponder.panHandlers}
      >
        <View style={styles.box} />
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  titleText: {
    fontSize: 14,
    lineHeight: 24,
    fontWeight: "bold"
  },
  box: {
    height: 150,
    width: 150,
    backgroundColor: "blue",
    borderRadius: 5
  }
});

export default App;

However, I want to console.log or do sone calculations when panresponder move so I tried modifying my opPanResponderMove but the blue box doesnt move anymore. I was wondering why?

My modified code:

onPanResponderMove: (event, gestureState) => {
        console.log(event);
        console.log(gestureState);
        Animated.event([
            null,
            { dx: pan.x, dy: pan.y }
          ])
      },

CodePudding user response:

There was an issue about your problem here

It said that

Reason was because Animation.event() only generates the function which is used from onPanResponderMove, it also needs the default arguments evt, gestureState

and here is the fix:

onPanResponderMove: (event, gestureState) => {
        console.log(event);
        console.log(gestureState);
        return Animated.event([
            null,
            { dx: pan.x, dy: pan.y }
          ])(event,gestureState);
      },
  • Related