react-native - 如何淡入一个组件而另一个淡出?

标签 react-native react-animated

在类组件中,我有两个 View ,一个作为占位符,一个用于图像。占位符显示直到某些状态发生变化(当图像完成加载时),然后显示图像。我正在尝试添加一些动画,并在状态更改时让图像淡入和占位符淡出。

下面是两个 View 的相关渲染函数:

renderImage = (filePath: string): JSX.Element => {
    const { isImageLoaded } = this.state;
    if (isImageLoaded) {
        return (
            <View style={Styles.imageContainer}>
                    <Image source={{ uri: filePath, cache: 'reload' }}/>
            </View>
        );
    }

    return (
        <View style={Styles.placeholderContainer}>
        </View>
    );
};

我知道我需要将 View 更改为 Animated.View 并具有淡入/淡出功能,如下所示:

Animated.timing(this.state.opacity, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start();

isImageLoaded 状态的 setState 回调中调用淡入/淡出函数的正确方法是什么?或者有没有一种方法可以触发动画而无需在 setState 中手动调用它们?

最佳答案

如果可以,我建议使用 react-native-reanimated (v2)。它具有使用 enteringexiting 属性完全适用于此用例的功能。 使用 reanimated 的示例:

if (shouldShow) {
   return(
      <Animated.View entering={FadeIn} exiting={FadeOut}>
         <Content/>
      </Animated.View>
   )
}

参见:https://www.youtube.com/watch?v=6UXfS6FI674

如果不可能,您必须构建自己的实现。可能是这样的:

handleHideAnimation = () => {
   Animated.timing(value, {
      toValue: 0,
      duration: 500,
    }).start(() => handleUnmountComponent);
}

关于react-native - 如何淡入一个组件而另一个淡出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70938407/

相关文章:

react-native - 在 React Navigation 5 中的另一个导航器中导航到屏幕

javascript - 如何在 React Native 中导航

javascript - 在 React Native 上使用 require 而不是 import 时出现红屏

react-native - React Native Animated API - 结合平移和旋转

javascript - 获得一个简单的滚动动画以在react-native中工作

react-native - react native : Animation not working properly on android

react-native - Metro bundler 错误 : Expected path […] to be relative to one of the project roots

javascript - 实现深层链接 url 导致 react 原生应用程序无法打开 android

react-native - 使用插值时如何初始设置不透明度

animation - 父边界内的可拖动 View