Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tìm hiểu Animations trong React Native: Animated API & LayoutAnimation


React Native cung cấp 2 hệ thống animation chính: Animated API (imperative, chi tiết) và LayoutAnimation (declarative, tự động). Bài viết tập trung vào 2 API core này.

1. Animated API - Kiểm soát chi tiết theo thời gian

Dùng Animated.Value hoặc Animated.ValueXY để drive animation. Hỗ trợ timing, spring, decay, sequence, parallel, stagger, loop.

Import

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

Ví dụ: Animate width & height khi bấm

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

class Animations extends Component {
  componentWillMount() {
    this.animatedWidth = new Animated.Value(50);
    this.animatedHeight = new Animated.Value(100);
  }

  animatedBox = () => {
    Animated.timing(this.animatedWidth, {
      toValue: 200,
      duration: 1000,
      useNativeDriver: false, // width/height không hỗ trợ native driver
    }).start();

    Animated.timing(this.animatedHeight, {
      toValue: 500,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };

  render() {
    const animatedStyle = {
      width: this.animatedWidth,
      height: this.animatedHeight,
    };

    return (
      
        
      
    );
  }
}

const styles = StyleSheet.create({
  container: { padding: 100, justifyContent: 'center', alignItems: 'center' },
  box: { backgroundColor: 'gray', width: 50, height: 100 },
});

export default Animations;

Các hàm chính của Animated

HàmMô tả
Animated.timing(value, config)Animation theo thời gian (duration, easing).
Animated.spring(value, config)Animation lò xo (tự nhiên, bouncy). Dùng useNativeDriver: true được.
Animated.decay(value, config)Animation giảm dần (fling, scroll).
Animated.sequence(animations[])Chạy tuần tự.
Animated.parallel(animations[])Chạy song song.
Animated.stagger(delay, animations[])Chạy song song nhưng delay từng cái.
Animated.loop(animation)Lặp vô hạn.
Animated.eventMap event (scroll, pan) vào Animated.Value.

Interpolation (Nội suy) - Key technique

const opacity = this.animatedWidth.interpolate({
  inputRange: [50, 200],
  outputRange: [1, 0.3],
});

const rotate = this.animatedWidth.interpolate({
  inputRange: [50, 200],
  outputRange: ['0deg', '360deg'],
});

useNativeDriver: true - Tăng hiệu suất

  • Chạy animation trên UI thread (native), không block JS thread.
  • Chỉ hỗ trợ: transform (translate, scale, rotate), opacity.
  • Không hỗ trợ: width, height, top, left, backgroundColor, borderRadius.
  • Luôn bật khi có thể cho animation mượt 60fps.

2. LayoutAnimation - Animation tự động cho layout thay đổi

Cấu hình animation toàn cục cho lần render tiếp theo khi layout thay đổi (state/props thay đổi size, position).

Import

import { LayoutAnimation, UIManager, Platform } from 'react-native';

Setup Android (bắt buộc)

if (Platform.OS === 'android') {
  UIManager.setLayoutAnimationEnabledExperimental &&
    UIManager.setLayoutAnimationEnabledExperimental(true);
}

Ví dụ: Tăng size circle khi bấm

import React, { Component } from 'react';
import { View, TouchableOpacity, StyleSheet, LayoutAnimation, UIManager, Platform } from 'react-native';

if (Platform.OS === 'android') {
  UIManager.setLayoutAnimationEnabledExperimental &&
    UIManager.setLayoutAnimationEnabledExperimental(true);
}

export default class App extends Component {
  state = { w: 50, h: 50 };

  animateCircle = () => {
    LayoutAnimation.spring(); // Cấu hình cho render TIẾP THEO
    this.setState({ w: this.state.w + 10, h: this.state.h + 10 });
  };

  render() {
    return (
      
        
      
    );
  }
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  circle: { borderRadius: '50%', backgroundColor: 'green' },
});

Các preset LayoutAnimation

PresetHiệu ứng
LayoutAnimation.spring()Lò xo, tự nhiên.
LayoutAnimation.easeInEaseOut()Nhẹ nhàng vào/ra.
LayoutAnimation.linear()Độ nhanh đều.
LayoutAnimation.configureNext(config)Tùy chỉnh chi tiết (create, update, delete).

So sánh: Khi nào dùng cái nào?

Tiêu chíAnimated APILayoutAnimation
Độ kiểm soátCao (mọi giá trị, timing, chaining)Thấp (chỉ layout change)
Hiệu suấtTốt (có native driver)Rất tốt (native only)
Phức tạp setupCaoThấp
Phù hợpAnimation phức tạp, gesture, loop, sequenceAdd/remove item, expand/collapse, reorder list

Thư viện animation hiện đại (Khuyên dùng cho production)

  • Reanimated 3 (worklet, chạy trên UI thread, API declarative, shared values) - **Tiêu chuẩn hiện tại**.
  • Moti / React Native Animatable - Đơn giản, declarative.
  • React Spring - Hook-based, cross-platform.

Lời khuyên: Dùng react-native-reanimated cho project thực tế. Animated API core chỉ phù hợp animation đơn giản hoặc học tập.