How to make draggable remember it's location in React Native

前端 未结 3 732
没有蜡笔的小新
没有蜡笔的小新 2021-01-05 09:40

I\'m learning about the animation and panresponder apis in react native. Following Animated Drag and Drop with React Native and the source

I want to extend the examp

3条回答
  •  旧时难觅i
    2021-01-05 10:25

    The logic in onPanResponderRelease is making it so that if the draggable is not in the dropzone when released, it is reset back to 0,0 (these are the lines causing it).

    Removing that logic alone isn't all you should do though. You should set the offset and reset the value of this.state.pan in onPanResponderRelease. To do this you need to track the value.

    In componentDidMount, add this:

    this.currentPanValue = {x: 0, y: 0};
    this.panListener = this.state.pan.addListener((value) => this.currentPanValue = value);
    

    Then, in componentWillUnmount:

    this.state.pan.removeListener(this.panListener);
    

    Now that you have the current value, you just add this to the PanResponder:

    onPanResponderRelease: (e, gestureState) => {
      this.state.pan.setOffset({x: this.currentPanValue.x, y: this.currentPanValue.y});
      this.state.pan.setValue({x: 0, y: 0});
    },
    

    It seems more complicated than it actually is. Basically you are just setting the offset from 0/0, then setting the value to 0/0 so that when you start moving it again after having released it before, it doesn't jump back to 0/0 before jumping back to where your finger is. It also makes sure you have its current position...which you will probably need at some point anyways.

提交回复
热议问题