ReactNative心跳动画(也可以做元素和文字缩放等)

57 阅读1分钟
import React, { useRef, useEffect } from 'react';
import { View, Text, StyleSheet, Animated } from 'react-native';

export const test = () => {
  const scaleValue = useRef(new Animated.Value(1)).current;

  useEffect(() => {
    // 定义心跳效果:快速放大,缓慢缩小
    const heartbeat = Animated.loop(
      Animated.sequence([
        Animated.timing(scaleValue, {
          toValue: 1.2, // 放大到1.2倍
          duration: 300, // 放大时间300ms
          useNativeDriver: true,
        }),
        Animated.timing(scaleValue, {
          toValue: 1, // 缩小回到原始大小
          duration: 300, // 缓慢缩小回去
          useNativeDriver: true,
        }),
      ])
    );

    // 启动心跳动画
    heartbeat.start();

    // 清除动画
    return () => heartbeat.stop();
  }, [scaleValue]);

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.box, { transform: [{ scale: scaleValue }] }]}>
        <Text style={styles.text}>❤️</Text>
      </Animated.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    width: 150,
    height: 150,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 50,
  },
});