react-nativepanresponder

React Native PanResponder Offset not working


I am trying to keep the pans Y offset when the user releases for the first time - I have looked around at how to accomplish this using the following methods but the offset is being ignored:

constructor(props) {
super(props);

this._pan = new Animated.ValueXY();

this._pan.addListener(value => {
  this._value = value;
  const {height: windowHeight} = Dimensions.get('window');
  this.props.onZoomProgress(
    Math.min(Math.max((value.y * -1) / windowHeight, 0), 0.5),
  );
});

this._panResponder = PanResponder.create({
  onMoveShouldSetResponderCapture: () => true,
  onMoveShouldSetPanResponderCapture: () => true,

  onPanResponderGrant: (e, gestureState) => {
    this._pan.setOffset({x: 0, y: gestureState.dy});
    this._pan.setValue({x: 0, y: 0});
  },

  onPanResponderMove: (e, gestureState) => {
    this._pan.setValue({y: gestureState.dy, x: 0});
    console.log(this._pan.y);
  },

  onPanResponderRelease: (e, gestureState) => {
    this._pan.extractOffset();
  },
});
}

This is a seperate component for this functionality so I am using this.props.onZoomProgress() to pass the value to use as the zoom state in my main component.

Cheers!


Solution

  • I'm not sure that this is your issue, but the part where you're directly accessing the internal value of your Animated.ValueXY looks suspect to me. Usually you'd add a listener to that if you want to get an actual number instead of just letting the animated value do the work.

    Something like this:

    this._pan.addListener(value => {
      this._value = value;
      const {height: windowHeight} = Dimensions.get('window');
      this.props.onZoomProgress(Math.min(Math.max((value.y * -1) / windowHeight, 0), 0.5))
    });
    

    The important thing to note is that you don't get the value of an Animated Value directly, you either assign the object to an Animated component and it updates magically, or you set up a listener, and get the value as it's passed in to you.