React Native Animated API - 结合平移和旋转

React Native Animated API - combine translate and rotation

最近在使用 React Native 动画时遇到了这个问题 API。

如图所示,一个卡片组件位于左上角,其翻转动画状态由rotateY值控制,移动动画由[=22=控制]translateX 和 translateY 值。

旋转轴心点似乎一直设置在卡片的原始位置。移动卡片后(更改 translateX 和 translateY 值),卡片翻转动画会参考其原始位置。

有没有办法调整旋转轴心点?或者,有没有办法为组件的位置设置动画而不是平移?谢谢。

终于成功了。事实证明,您可以在不使用翻译 属性 的情况下通过向动画值添加侦听器并相应地更新组件状态来为组件位置更改设置动画:

  1. 在构造函数中,设置卡片组件初始位置和cardPos动画值。

  2. 在 componentDidMount 函数中,将侦听器附加到动画值。当动画值改变时,更新组件状态。

  3. 在渲染函数中将组件根值样式设置为position:"absolute",实际位置与组件状态中的值同步。

constructor(props){
  super(props);
  // set card initial position as component state
  this.state = {
      cardPosX: this.props.position.x,
      cardPosY: this.props.position.y
  };
  this.flipAnimatedValue = new Animated.Value(
      this.props.isFacingUp ? 180 : 0
    );
  this.flipAnimatedInterpolate = this.flipAnimatedValue.interpolate({
    inputRange: [0, 90, 180],
    outputRange: ["0deg", "90deg", "0deg"]
  });
  // create animated value for card Position X and Y
  this.cardPosXAnimatedValue = new Animated.Value(this.props.position.x);
  this.cardPosYAnimatedValue = new Animated.Value(this.props.position.y);
}

 componentDidMount() {
    // addListener for cardPos Animated Value
    // when animated values change, update the component state
    this.cardPosXAnimatedValue.addListener(({ value }) => {
      this.setState({ cardPosX: value });
    });
    this.cardPosYAnimatedValue.addListener(({ value }) => {
      this.setState({ cardPosY: value });
    });
 }
 
 render(){
  return (
     <View
          style={{
            width: this.cardWidth,
            height: this.cardHeight,
            position: "absolute",
            top: this.state.cardPosY, //card position sync with animated value
            left: this.state.cardPosX
          }}
        >
        ... //child components
     </View>
  );
 }