我有以下代码:
const ScrollScreen = () => {
const scrollY = useRef(new Animated.Value(0)).current;
const paddingTop = scrollY.interpolate({
inputRange: [200, 400],
outputRange: [0, 100],
extrapolate: "clamp",
});
return (
<ScrollView
stickyHeaderIndices={[3]}
>
<SomeOtherComponent1 />
<SomeOtherComponent2 />
<SomeOtherComponent3 />
<Animated.View style={{ paddingTop }}>
<Text>Some text </Text>
</Animated.View>
</ScrollView>
);
};
这个想法是,当我们向上滚动时,逐渐向
Text
组件添加内边距,这样当滚动超过 400 像素时,它的 paddingTop
为 100 像素,并且永远不会接触屏幕顶部,即使通过 stickyHeaderIndices
属性修复。
我注意到,如果我们缓慢向上滚动,效果会很好,但如果我们快速向上滑动,
Text
组件将首先一直到达屏幕顶部,然后再下降到预期的 100 像素。
我猜插值似乎不够快,但是有什么解决方案可以解决这个问题以实现快速滚动吗?
你能尝试这样的事情吗?
import React, { useRef } from 'react';
import { Animated, ScrollView, View, Text, StyleSheet } from 'react-native';
const MyScrollView = () => {
const scrollY = useRef(new Animated.Value(0)).current;
const paddingTop = scrollY.interpolate({
inputRange: [0, 50], // Adjust the input range as needed
outputRange: [0, 20], // Adjust the output range as needed
extrapolate: 'clamp',
});
return (
<Animated.ScrollView
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
{ useNativeDriver: false }
)}
scrollEventThrottle={16}
>
<Animated.View style={[styles.item, { paddingTop }]}>
<Text>First Item</Text>
</Animated.View>
<View style={styles.item}>
<Text>Second Item</Text>
</View>
<View style={styles.item}>
<Text>Third Item</Text>
</View>
{/* Add more items as needed */}
</Animated.ScrollView>
);
};
const styles = StyleSheet.create({
item: {
height: 100,
justifyContent: 'center',
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: '#ccc',
},
});
export default MyScrollView;