0

I am learing about animation and react-native-gesture-handler in React Native on Youtube by this tutorial: https://www.youtube.com/watch?v=aoENL4gF9rE&t=201s.

The thing is I have the trouble in understanding these code, it will move the red box horizontally when user drag it.

Picture from app

class AnimApp extends Component {
  constructor() {
    this.translateX = new Animated.Value(0);

    this.onGestureEvent = Animated.event([
      {
        nativeEvent: {
          translationX: this.translateX,
        },
      },
    ]);
  }
  render() {
    return (
      <View style={styles.container}>
        <PanGestureHandler onGestureEvent={this.onGestureEvent}>
          <Animated.View
            style={{...styles.box, transform: [{translateX: this.translateX}]}}
          />
        </PanGestureHandler>
      </View>
    );
  }
}
export default AnimApp;

I know in the transform part, the translateX property is using this.translateX to move the view, but I dont know how the this.translateX have its value. I dont see any value is assigned to this.translateX. I have console.log(this.translateX) and its value changes when dragging, just dont know how the flow is.

1 Answers1

0

You can extract the native events from the gesture and assign it to Animated value.

In this case the value is getting from the PanGestureHandler

this.onGestureEvent = Animated.event([
      {
        nativeEvent: {
          translationX: this.translateX,
        },
      },
    ]);

This onGestureEvent passes a event object to the Animated value, from there we are extracting the event value.I am adding a link for others Animated.event

Thakur Karthik
  • 3,034
  • 3
  • 15
  • 24
  • This is how i understand: this.translateX is assigned to translationX, so this.translateX's value is still 0 because it's not assigned from anywhere – Phi Anh Kiệt Sep 16 '19 at 10:00
  • Try to console the event and observe its structure.I think the translationX is assigned to this.translateX ,it is a weird structure for sure.https://facebook.github.io/react-native/docs/animated#event – Thakur Karthik Sep 16 '19 at 10:03
  • Is it possible to add some sort of checks this onGestureFunciton? See this please https://stackoverflow.com/questions/64330969/stop-dragging-after-a-limit-has-reached –  Oct 13 '20 at 08:50