Cours React Native · Module 10: Animations

API Animated - Les bases de l'animation

2 min de lecture ·
Dans cette leçon3

Bienvenue dans la Galerie des Courants ! Apprends à animer les éléments comme les courants de l'océan !

Animation de base

import { Animated, Pressable, StyleSheet } from 'react-native';
import { useRef } from 'react';

function FadeInView() {
  const fadeAnim = useRef(new Animated.Value(0)).current;

  const fadeIn = () => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start();
  };

  const fadeOut = () => {
    Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
  };

  return (
    <View>
      <Animated.View style={[styles.box, { opacity: fadeAnim }]}>
        <Text>Élément en fondu</Text>
      </Animated.View>
      <Pressable onPress={fadeIn}><Text>Afficher</Text></Pressable>
      <Pressable onPress={fadeOut}><Text>Masquer</Text></Pressable>
    </View>
  );
}

Différents types d'animation

// timing - animation linéaire
Animated.timing(value, { toValue: 1, duration: 300, useNativeDriver: true });

// spring - effet de ressort
Animated.spring(value, { toValue: 1, friction: 5, tension: 40, useNativeDriver: true });

// decay - ralentissement
Animated.decay(value, { velocity: 0.5, deceleration: 0.997, useNativeDriver: true });

// Combiner les animations
Animated.sequence([anim1, anim2]); // l'une après l'autre
Animated.parallel([anim1, anim2]); // simultanément
Animated.stagger(100, [anim1, anim2, anim3]); // avec un décalage

Interpolation

const animValue = useRef(new Animated.Value(0)).current;

const rotation = animValue.interpolate({
  inputRange: [0, 1],
  outputRange: ['0deg', '360deg'],
});

const backgroundColor = animValue.interpolate({
  inputRange: [0, 0.5, 1],
  outputRange: ['#1a5276', '#00d4ff', '#1a5276'],
});

<Animated.View style={{ transform: [{ rotate: rotation }], backgroundColor }} />
Code de cette leçon : App.tsx
import React, { useRef } from 'react';
import { Animated, View, Text, Pressable, StyleSheet } from 'react-native';

export default function App() {
  // TODO : créer une valeur animée qui démarre à 0
  //       utiliser useRef pour qu'elle survive aux re-rendus :
  //       const fadeAnim = useRef(new Animated.Value(0)).current;

  const fadeIn = () => {
    // TODO : exécuter Animated.timing sur fadeAnim :
    //       toValue: 1, duration: 500, useNativeDriver: true
    //       pense à appeler .start() à la fin

  };

  const fadeOut = () => {
    // TODO : exécuter Animated.timing sur fadeAnim :
    //       toValue: 0, duration: 500, useNativeDriver: true, puis .start()

  };

  return (
    <View style={styles.container}>
      {/* TODO : lier fadeAnim au style opacity de la vue animée :
          style={[styles.box, { opacity: fadeAnim }]} */}
      <Animated.View style={styles.box}>
        <Text style={styles.boxText}>Courant océanique</Text>
      </Animated.View>

      <Pressable style={styles.button} onPress={fadeIn}>
        <Text style={styles.buttonText}>Afficher</Text>
      </Pressable>
      <Pressable style={styles.button} onPress={fadeOut}>
        <Text style={styles.buttonText}>Masquer</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1a5276',
  },
  box: {
    width: 200,
    height: 200,
    borderRadius: 16,
    backgroundColor: '#00d4ff',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 24,
  },
  boxText: {
    color: '#0a2540',
    fontSize: 18,
    fontWeight: '700',
  },
  button: {
    paddingVertical: 12,
    paddingHorizontal: 28,
    borderRadius: 8,
    backgroundColor: '#2980b9',
    marginVertical: 6,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Comment crée-t-on une valeur animée ?

  2. 2. Pourquoi utilise-t-on useRef avec Animated.Value ?

Voici 2 des 7 questions de cette leçon. Réponds aux autres dans le jeu.

Tâches pratiques dans le jeu

  • Clique dans l'ordre

    Clique sur les éléments de Animated.timing :

  • Tri horizontal

    Ordonne le démarrage d'une animation avec un callback :

  • Tri vertical

    Ordonne l'interpolation :

  • Éditeur de code

    Complète le code de FadeInView.

  1. QuestionAnimated.Value
  2. QuestionuseRef pour Animated
  3. Clique dans l'ordreAnimated.timing
  4. QuestionuseNativeDriver
  5. QuestionAnimated.spring
  6. Remets dans l'ordrecallback start
  7. QuestionAnimated.sequence
  8. QuestionAnimated.parallel
  9. QuestionAnimated.stagger
  10. Remets dans l'ordreinterpolate
  11. Exercice de codeAnimation de fondu

Articles utiles