【问题标题】:When using React Native Animated, it possible to animate the offset?使用 React Native Animated 时,可以为偏移设置动画吗?
【发布时间】:2017-02-06 12:19:07
【问题描述】:

我正在尝试创建一个动画拖放功能,如下所示:http://moduscreate.com/animated_drag_and_drop_with_react_native/

我想更改它,以便当用户开始触摸时,对象向上移动,使其不再隐藏在他们的手指下。我希望这个动作是动画的,但我也想在动画期间跟踪平移手势。

现在,只要用户不移动手指,动画就可以正常工作。当触摸开始时,我正在使用此代码为对象设置动画:

onPanResponderStart: (e, gesture) => {
  Animated.spring(
    this.state.pan,
    {
      ...animationConstants,
      toValue: { x: 0, y: -70 },
    }
  ).start((status) => {
    // This part ensures that the offset and value are
    // set correctly after the animation.
    this.state.pan.y.setOffset(-70);
    this.state.pan.y.setValue(0);
  });
},

但只要他们移动手指,它就会取消动画并跳到顶部。我将此代码用于onPanResponderMove

onPanResponderMove: Animated.event([null, {
  dx: this.state.pan.x,
  dy: this.state.pan.y
}]),

我希望动画继续播放,即使用户正在移动手指。

如何更改代码以便为“偏移”而不是“值”设置动画?如果Animated.spring 可以选择使用toOffset: {x: ..., y: ...} 以及toValue,我想我可以解决这个问题。但我不认为它有这个,我不确定我应该如何模仿它。

【问题讨论】:

  • 这是一个旧线程,但如果有人到达它:我想你可以使用 flattenOffset() 方法facebook.github.io/react-native/docs/…。然后将偏移量合并到值中,您可以对值进行动画处理,包括偏移量。

标签: javascript ios reactjs animation mobile


【解决方案1】:

我想通了。我不确定性能,但它似乎工作正常。

我设置了一个单独的Animated.Value 来为偏移设置动画。我刚刚使用addListener 添加了一个回调,它调用setOffset 为值设置动画。

constructor(props){
  super(props);

  this.state = {
    pan: new Animated.ValueXY(),
    offset: new Animated.Value(0)
  };

  this.state.offset.addListener((value) => {
    this.state.pan.y.setOffset(value.value);
  });

  this.panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onPanResponderStart: (e, gesture) => {
      Animated.spring(
        this.state.offset, 
        { toValue: -70 }
      ).start();
    },
    onPanResponderMove: Animated.event([null, {
      dx: this.state.pan.x,
      dy: this.state.pan.y
    }]),
    onPanResponderRelease: (e, gesture) => {
      Animated.spring(
        this.state.pan,
        {
          toValue: { x: 0, y: 0 }
        }
      ).start();

      Animated.spring(
        this.state.offset,
        { toValue: 0 }
      ).start();
    }
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多