Animated de React Native permite crear animaciones y transiciones fluidas dentro de la aplicación, proporcionando una forma sencilla y poderosa de hacer que los elementos se muevan, cambien de tamaño, color o cualquier otra propiedad de manera animada.
Animated, no es un componente en React Native.
Es un módulo o API que proporciona funciones y componentes para crear animaciones.
Aunque se usa como un componente, su propósito principal es facilitar la creación de animaciones fluidas y eficientes en aplicaciones móviles.
Animated puede animar propiedades de cualquier componente React Native.
Es necesario utilizar los tipos de animaciones proporcionadas por Animated, como Animated.Value y Animated.timing.
import React, { useState, useEffect } from 'react';
import { View, Text, Animated, StyleSheet, Button } from 'react-native';
const App = () => {
const [fadeAnim] = useState(new Animated.Value(0)); // Iniciar valor de opacidad en 0
const fadeIn = () => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 2000, // Duración de la animación en milisegundos
useNativeDriver: true,
}).start();
};
return (
<View style={styles.container}>
<Animated.View style={[styles.box, { opacity: fadeAnim }]}>
<Text style={styles.text}>Texto con animación de opacidad</Text>
</Animated.View>
<Button title="Fade In" onPress={fadeIn} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
box: {
width: 200,
height: 200,
backgroundColor: 'skyblue',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 20,
},
text: {
fontSize: 18,
color: 'white',
},
});
export default App; Animated.Value: Se usa para definir valores animables (por ejemplo, opacidad, posición, escala).Animated.timing: Define animaciones con un tiempo determinado. Es la forma más común de animar valores.Animated.spring: Define animaciones de tipo “resorte”, con un comportamiento de rebote.Animated.decay: Crea animaciones con un movimiento gradual.useNativeDriver: Define si la animación se ejecutará en el hilo nativo, mejorando el rendimiento.En este ejemplo, moveremos un componente en la pantalla usando Animated.Value y Animated.timing.
import React, { useState } from 'react';
import { View, Animated, StyleSheet, Button } from 'react-native';
const App = () => {
const [moveAnim] = useState(new Animated.Value(0)); // Valor inicial de la posición X
const moveBox = () => {
Animated.timing(moveAnim, {
toValue: 300, // Moverlo a la derecha 300 unidades
duration: 1000, // Duración de la animación
useNativeDriver: true,
}).start();
};
return (
<View style={styles.container}>
<Animated.View
style={[styles.box, { transform: [{ translateX: moveAnim }] }]} // Aplicar transformación
/>
<Button title="Mover caja" onPress={moveBox} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
box: {
width: 100,
height: 100,
backgroundColor: 'tomato',
marginBottom: 20,
},
});
export default App; Animated.springSi deseas un comportamiento de animación más natural, puedes usar Animated.spring.
import React, { useState } from 'react';
import { View, Animated, StyleSheet, Button } from 'react-native';
const App = () => {
const [springAnim] = useState(new Animated.Value(0));
const springMove = () => {
Animated.spring(springAnim, {
toValue: 1, // Finalizar en el valor 1
friction: 2, // Ajustar la fricción (rebote)
tension: 100, // Ajustar la tensión
useNativeDriver: true,
}).start();
};
return (
<View style={styles.container}>
<Animated.View
style={[styles.box, { transform: [{ scale: springAnim }] }]}
/>
<Button title="Animación de resorte" onPress={springMove} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
box: {
width: 100,
height: 100,
backgroundColor: 'green',
marginBottom: 20,
},
});
export default App; useNativeDriver: Siempre que sea posible, usa useNativeDriver: true para mover las animaciones al hilo nativo, mejorando el rendimiento.Animated de React Native es una herramienta poderosa para agregar animaciones y transiciones fluidas a tus aplicaciones. Permite animar propiedades como la opacidad, el tamaño, la posición y muchas más, lo que mejora significativamente la experiencia de usuario. Además, puedes usar diferentes tipos de animación, como timing, spring y decay, según el tipo de animación que desees lograr.