在类组件中,我有两个 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)
。它具有使用 entering
和 exiting
属性完全适用于此用例的功能。
使用 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/