如何根据父级的当前拖动位置转换视图偏移

时间:2019-01-05 21:11:01

标签: javascript react-native pan

我在这里有一个非常具体的案例,有点让我迷上了如何计算才能使它起作用

我在页面上显示了这张卡

enter image description here

使用这些样式呈现...

-------- main card --------
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
height,
shadowColor: "#455B63",
shadowOffset: {
  width: 0,
  height: 0,
},
shadowOpacity: 0.33,
shadowRadius: 16,
borderBottomLeftRadius: 12,
borderBottomRightRadius: 12

-------- content view --------
backgroundColor: '#fff',
paddingVertical: 14,
paddingHorizontal: 20,
height: height * 2

已附加此动画...

Animated.spring(this.state.placeCard,{
    toValue: {x: 0, y: deviceHeight - placeCardClosedHeight},
    duration: 350,
}).start();

内容视图的动画状态设置为状态

new Animated.ValueXY({x: 0, y: -(Math.round(deviceHeight / 2) - 160)})

我正在尝试使其动画化此布局

enter image description here

我为处理所有卡片样式设置的操作员是这个

this._placeCardPanResponder = PanResponder.create({
  onMoveShouldSetPanResponderCapture: (evt, gestureState) => gestureState.dx != 0 && gestureState.dy != 0,
  onPanResponderGrant: (evt, gestureState) => {
    this.setState({
      placeCardTopOffset: this.state.placeCard.__getValue().y
    })
  },
  onPanResponderMove: (evt, gestureState) => {
    let y = gestureState.dy;
    const { placeCardTopOffset } = this.state;
    if (y + placeCardTopOffset <= 0) {
      y = 0
    } else if (y + placeCardTopOffset >= deviceHeight - placeCardClosedHeight) {
      y = deviceHeight - placeCardClosedHeight
    } else {
      y = y + placeCardTopOffset;
    }
    this.state.placeCard.setValue({x: 0, y});
  },
  onPanResponderRelease: (evt, gestureState) => {
    if (gestureState.dy < 0) {
      if (this.state.placeCard.__getValue().y > 0) {
        Animated.timing(
          this.state.placeCard,
          {
            toValue: {x: 0, y: 0},
            duration: 175,
          }
        ).start();
      }
    }
    if (gestureState.dy > 0) {
      if (this.state.placeCard.__getValue().y < deviceHeight - placeCardClosedHeight) {
        Animated.timing(
          this.state.placeCard,
          {
            toValue: {x: 0, y: deviceHeight - placeCardClosedHeight},
            duration: 175,
          }
        ).start();
      }
    }
  }
});

当卡片在页面上全高时,内容视图将像这样显示动画

Animated.timing(
  this.state.placeCardContent,
  {
    toValue: {x: 0, y: 0},
    duration: 175,
  }
).start();

我有一个零食设置可以炫耀

如果单击图像,您将看到预期的动画,但是如果拖动,将看到如何处理拖动。我遇到的问题是试图找出与拖动主视图时对该内容视图进行动画处理有关的数学方法。

https://snack.expo.io/B1lhq5Rb4

1 个答案:

答案 0 :(得分:0)

我忘了记住react-native的{​​{1}} API具有Animated函数的功能这一事实,该功能是专为这项任务而设计的。

这是使此工作有效的代码...

.interpolate()

您可以在这个零食示例中看到此方法

https://snack.expo.io/@jordanr/carddrag