编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

react native 淡入淡出效果(react native 页面切换动画)

wxchong 2024-08-24 01:40:34 开源技术 10 ℃ 0 评论

在React Native中,你可以使用内置的动画API(如Animated)来实现淡入淡出的效果。

下面是一个示例,演示如何使用Animated来实现淡入淡出效果:

import React, { useEffect, useRef } from 'react';
import { View, Animated, StyleSheet, TouchableOpacity, Text } from 'react-native';

const FadeInOut = () => {
  const fadeAnim = useRef(new Animated.Value(0)).current;

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

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

  useEffect(() => {
    fadeIn();

    return () => {
      fadeOut();
    };
  }, []);

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.box, { opacity: fadeAnim }]}>
        <Text style={styles.text}>Hello, Fade In Fade Out</Text>
      </Animated.View>
      <TouchableOpacity style={styles.button} onPress={fadeOut}>
        <Text style={styles.buttonText}>Fade Out</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.button} onPress={fadeIn}>
        <Text style={styles.buttonText}>Fade In</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    width: 200,
    height: 200,
    backgroundColor: 'blue',
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    color: 'white',
    fontSize: 20,
  },
  button: {
    marginTop: 10,
    padding: 10,
    backgroundColor: 'gray',
    borderRadius: 5,
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
  },
});

export default FadeInOut;

在上面的示例中,我们使用Animated库中的Animated.View来包裹要淡入淡出的内容。通过创建一个fadeAnim的动画值,并在组件加载时执行淡入动画(fadeIn)并在组件卸载时执行淡出动画(fadeOut)。在Animated.View的style属性中,设置opacity为fadeAnim,这样可以根据动画值自动调整透明度,实现淡入淡出效果。

通过点击"Fade Out"和"Fade In"按钮,你可以手动触发淡出和淡入的动画效果。

你可以根据需要调整动画的配置(如持续时间、使用原生驱动等),以及自定义包裹内容的样式和动画效果。

#头条文章养成计划#

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表