问题描述
关于如何实现Animated.diffClamp的任何代码示例?
Any code example of how to implement Animated.diffClamp?
我正在尝试创建类似于Google Play应用中的标题滚动动画。当您开始向下滚动时,我已经隐藏了标题,但是问题是我想在开始向上滚动时再次显示标题,它仅在您到达视图顶部时显示。
I'm trying to create a header scroll animation like the one featured in the google play app. I already hide the header when you start scrolling down, but the problem is that I want to show the header again as soon as you start scrolling up, it shows only when you reach the top of the view.
class Services extends Component {
constructor(props){
super(props);
this.state = {
scrollY : new Animated.Value(0),
}
}
renderScrollViewContent(){
return (
<View style={styles.scrollViewContent}>
</View>
)
}
render() {
const headerHeight = this.state.scrollY.interpolate({
inputRange: [0, 60],
outputRange: [0, -60],
extrapolate: 'clamp'
});
return (
<View style={styles.container}>
<ScrollView style={styles.container}
scrollEventThrottle={16}
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {y: this.state.scrollY}}}]
)}
>
{this.renderScrollViewContent()}
</ScrollView>
<Animated.View style={[styles.header, {top: headerHeight}]}>
<View style={styles.bar}>
<Text style={styles.title}>Title</Text>
</View>
</Animated.View>
</View>
);
}
}
推荐答案
我们正是为此用例添加了此内容。这是文档页面
We added this exactly for this use case. Here's the doc page https://facebook.github.io/react-native/docs/animated.html#diffclamp
我还建议将其与翻译转换配合使用(更好的性能,可与本机驱动程序一起使用)。这是您使用它的示例渲染:
I also recommend using it with a translate transform (better perf and can be used with native driver). Here's your example render using it:
const headerTranslate = Animated.diffClamp(this.state.scrollY, 0, 60)
.interpolate({
inputRange: [0, 1],
outputRange: [0, -1],
});
return (
<View style={styles.container}>
<ScrollView style={styles.container}
scrollEventThrottle={16}
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {y: this.state.scrollY}}}]
)}
>
{this.renderScrollViewContent()}
</ScrollView>
<Animated.View style={[styles.header, {transform: [{translateY: headerTranslate}]}]}>
<View style={styles.bar}>
<Text style={styles.title}>Title</Text>
</View>
</Animated.View>
</View>
);
它的工作原理是将滚动位置传递给diffClamp,以便在之后将其固定在0到60之间我们使用插值法将值设为负(我们希望它向上转换)。
How it works is we pass the scroll position to diffClamp so it is clamped between 0 and 60, after we use interpolate to make the value negative (we want it to translate up).
这篇关于如何在React Native中使用Animated.diffClamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!