我试图让这张卡在每次组件加载时淡入,并在使用钩子卸载后淡出,但我没能做到这一点,迫切需要有人的帮助。请教我如何在每次加载和卸载这张卡时使用
hooks
为其设置动画
这是我的组件:
import React, { useState } from "react";
const Home = (props) => {
const renderCard = ({ item }) => {
return (
//I am trying to add a fadein to this everytime it loads and fadout when It unmounts
<View>
<Text style={styles.day}>{item}</Text>
<MealCards
item={state[item]}
navigation={navigation}
onChange={onChange}
/>
<View style={styles.divider} />
</View>
);
};
return (
<FlatList
data={days}
keyExtractor={(item) => item}
showsHorizontalScrollIndicator={false}
renderItem={renderCard}
/>
);
};
我认为最好的方法是使用 Reanimated。
import Animated, { FadeIn, FadeOut } from 'react-native-reanimated';
<Animated.View
key={'uniqueKey'}
entering={FadeIn.duration(400)}
exiting={FadeOut.duration(400)}
/>
额外提示:如果您想重新触发动画,您只需更改组件关键道具;)
将组件包裹在
Animated.View
中,并使用不透明度为其提供淡入动画效果:https://reactnative.dev/docs/animated。
类似的东西
const [fadeAnim] = useState(new Animated.Value(0));
React.useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 1000,
}).start();
}, []);
return (
<Animated.View
style={{
opacity: fadeAnim,
}}
>
{props.children}
</Animated.View>
);
上面的代码用于淡入。淡出将在 useEffect 的返回函数中完成。
基于 @Benjamin Godlove 的回答,这是一个完全有效的淡入/淡出示例。
我发现由于 useEffect return 语句而尝试淡出是行不通的(我相信组件在动画有时间运行之前卸载并取消渲染),因此我保持组件已安装并仅使用切换。
type Props = {
children: React.ReactNode;
visible: boolean;
};
function FadePanel({children, visible}:Props){
const fadeAnim = useRef(new Animated.Value(0)).current;
React.useEffect(() => {
if (visible) {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
}).start();
} else if (!visible) {
Animated.timing(fadeAnim, {
toValue: 0,
duration: 1000,
useNativeDriver: true,
}).start();
}
}, [visible]);
return (
<Animated.View
style={{
opacity:fadeAnim
}}
>
{children}
</Animated.View>
)
}
react-native-fadeview-wrapper
的库,您可以轻松覆盖所有淡入淡出动画,并且它也是可定制的。
<FadeView visible={isVisible}>
{/** any components of yours */}
</FadeView>
如果您想要一个简单的淡入淡出动画,这个包就可以发挥魔力。 https://github.com/NischalShahi/reanimated-crossfade-images