React Native 中简单的向上移动动画

问题描述 投票:0回答:1

我是 React Native (Expo Go) 的初学者,我正在尝试制作以下动画:

应用程序启动时,图像从屏幕中间的随机位置开始,然后向上移动,直到超出范围。 一旦出界,图像就会从屏幕底部出现。

我遇到的麻烦是图像仅在第一个动画中途开始。

我尝试过不同的 Reanimated 库,例如 withRepeat 和 withTiming,但没有效果。

react-native
1个回答
0
投票

尝试这样 小吃链接:https://snack.expo.dev/@cyberking40/7d4562

import React, { Component } from 'react';
import { View, Image, Animated, Dimensions } from 'react-native';

const { height } = Dimensions.get('window');

class AnimatedImage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      position: new Animated.Value(height / 2), // Initial position halfway up the screen
    };
  }

  componentDidMount() {
    this.moveImage();
  }

  moveImage = () => {
    Animated.timing(this.state.position, {
      toValue: -height, // Move the image to the top of the screen
      duration: 3000, // Adjust the duration as needed
      useNativeDriver: false,
    }).start(() => {
      // When animation completes, reset position and start again
      this.state.position.setValue(height); // Move the image to the bottom of the screen
      this.moveImage();
    });
  };

  render() {
    const { position } = this.state;
    return (
      <Animated.View style={{ position: 'absolute', top: position }}>
        <Image source={require('./assets/snack-icon.png')} />
      </Animated.View>
    );
  }
}

export default AnimatedImage;
© www.soinside.com 2019 - 2024. All rights reserved.