在我的反应原生应用程序中,我正在尝试对视图的不透明度进行动画处理。当我滚动时,我看到动画完成了这项工作,但它同时在闪烁。我不知道为什么。
视频示例 : https://cdn.discordapp.com/attachments/102861040538120192/560165613092339734/video.mov
这是我制作的代码
const Scrollable = () => {
const largeHeaderSize = useState({
height: 0,
y: 0
});
const animatedValueScrollY = new Animated.Value(largeHeaderSize.height);
const [scrollY, setScrollY] = useState(0);
const headerOpacity = animatedValueScrollY.interpolate({
inputRange: [0, largeHeaderSize.height],
outputRange: [1, 0],
extrapolate: "clamp"
});
return (
<SafeAreaView>
<Animated.View
style={{
borderBottomWidth:
scrollY >= largeHeaderSize.height ? StyleSheet.hairlineWidth : 0
}}>
<View>
<Animated.View style={{ zIndex: 1, opacity: headerOpacity }}>
<Text>Title</Text>
</Animated.View>
</View>
</Animated.View>
<Animated.ScrollView
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: animatedValueScrollY } } }],
{
useNativeDriver: true,
listener: event => setScrollY(event.nativeEvent.contentOffset.y)
}
)}
scrollEventThrottle={16}
contentInset={{
top: 0,
bottom: 50
}}
contentOffset={{
y: 0
}}
/>
</SafeAreaView>
);
};
我该如何解决这个问题?
解决方案是使用 useRef 钩子,如下所示:
const animatedValueScrollY = useRef(new Animated.Value(0))
const headerOpacity = animatedValueScrollY.current.interpolate({
inputRange: [0, largeHeaderSize.height],
outputRange: [1, 0],
extrapolate: 'clamp'
});