Простая анимация в react-native: перемещение изображения слева направо - PullRequest
0 голосов
/ 04 августа 2020

Может ли кто-нибудь поделиться примером кода для реактивной анимации, которая перемещает изображение слева направо, затем возвращается к начальной точке и повторяет движение?

Обновление:

Ответ ниже очень помог, но не сработал. Я использовал его для создания следующей анимации, которая перемещает изображение слева направо (я использую RN 0.62.2).

import React from 'react'
import { StyleSheet, View, Animated, Easing } from 'react-native';

const test = require('../images/test.png');

export class Splash extends React.Component {
    constructor(props) {
        super(props);
        this.state = { xValue: new Animated.Value(-100) }
    }

  moveLR = () => {
        Animated.timing(
          this.state.xValue,
          {
            toValue: 100,
            duration: 1000, // the duration of the animation
            easing: Easing.linear, // the style of animation
            useNativeDriver: true
          }
        ).start();
  }

  moveRL = () => {
    Animated.timing(
      this.state.xValue,
      {
        toValue: -100,
        duration: 3000, // the duration of the animation
        easing: Easing.linear, // the style of animation
        useNativeDriver: true
      }
    ).start();
  }

  componentDidMount = () => {
    this.moveLR();
  }

  render = () => {
    return (
      <View style={styles.mainContainer}>
        <Animated.Image
            style={{ width: 170, height: 146 }}
            source={test}
            style={{ width: 170, height: 146,
                transform: [{ translateX: this.state.xValue }] }}>
        </Animated.Image>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  animationView: {
    backgroundColor: 'red',
    width: 100,
    height: 100
  }
})

1 Ответ

1 голос
/ 05 августа 2020

Обновление от Йоси:

Приведенный ниже код не работал у меня в RN 0.62.2. Я принимаю ответ, но я его изменил, и теперь в вопрос включен работающий код.

Исходный ответ:

Прежде чем начать, мне нужно познакомить вас с двумя типы значений для анимированных анимаций:

Animated.Value (), где мы определяем значение, полезно, когда мы хотим переместить элемент по одной оси (X или Y), изменить размер элемента , et c. Это то, что мы будем использовать здесь, в этой главе, и это то, что используется чаще всего.

Animated.ValueXY (), где мы определяем вектор, полезный для перемещения элемента по двум осям.

С этими значениями мы можем определить несколько типов анимированных анимаций. Мы будем открывать их один за другим, каждый раз тестируя. в этом примере я буду говорить только об Animated.timing (). Здесь вы можете увидеть пример кода, который будет перемещать красную рамку слева направо и останавливаться, когда пользователь решит, вы можете попробовать и определить, сработало ли это для вы:

// Test.js

import React from 'react'
import { StyleSheet, View, Animated } from 'react-native'

class Test extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
    leftPosition : new Animated.Value (0)
  }
  
  const stopAnimation = () => {
    this.setState({
      leftPosition : this.state.leftPosition // this forces the left position to remain the same considering the `componentDidMount` method already happened
    })
  }
  mooveLR (){
    Animated.timing(
      this.state.leftPosition,
      {
        toValue: 100,
        duration: 3000, // the duration of the animation
        easing: Easing.linear, // the style of animation 
      }
    ).start() // starts this annimation once this method is called
  }
  
  mooveRL (){
    Animated.timing(
      this.state.leftPosition,
      {
        toValue: 0,
        duration: 3000, // the duration of the animation
        easing: Easing.linear, // the style of animation 
      }
    ).start() // starts this annimation once this method is called
  }
  
  componentDidMount(){
    this.state.leftPosition === 0 ? mooveLR () : mooveRL () // repeats always when the red box return to its initial position : leftPosition === 0
  }
  render() {
    return (
      <View style={styles.main_container}>
        <Animated.View style={[styles.animation_view], left : this.state.leftPosition}>
        </Animated.View>
        <TouchableOpacity onPress = { () => this.stopAnimation ()}>
          <Text>Stop animation</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main_container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  animation_view: {
    backgroundColor: 'red',
    width: 100,
    height: 100
  }
})

export default Test

Надеюсь, это поможет С уважением

...