React-Native列表顶部随滑动渐变效果
概要
本篇文章的内容在于通过React-Native实现一个列表顶部随滑动渐变的效果。
一开始使用state来保存顶部需要变动样式的值,后来发现由于RN对state状态改变时的处理机制,导致页面呈现的效果不具实时性且不太流畅,所以改进使用了RN自己提供的Animated动画和ScrollView滑动组件。
顶部view区域颜色随滑动渐变
通过Animated自己附带的事件nativeEvent获取ScrollView的滑动距离
//声明滑动动画事件
this.animatedEvent = Animated.event(
[
{
nativeEvent: {
contentOffset: {
y: this.state.navBackColorOffset } //将y值保存到state中背景色偏移距离的值上
}
}
]
)
通过state中保存的偏移距离navBackColorOffset,映射到动画中,定义输入区间和输出区间的值(设置useNativeDriver为true,使用原生驱动提升效率)。
//生成背景色动画输入输出区间
const navBackColorOffset = this.state.navBackColorOffset
this.backgroundAnimated = navBackColorOffset.interpolate({
inputRange: [0, this.changeNavHeight],
outputRange: ['#F2F740', '#FA5D4D'],
extrapolate: 'clamp', //阻止输出值超过outputRange
useNativeDriver: true,
})
当ScrollView开始滑动后,调用onScroll中绑定的this.animatedEvent方法,记录偏移量并保存到state中。
<ScrollView
style={
{
flex:1, width:width }}
scrollEventThrottle={
1}
onScroll={
this.animatedEvent} //滑动监听事件
showsVerticalScrollIndicator={
false}
>
...
</ScrollView>
将this.backgroundAnimated的输出赋值给顶部区域的背景色样式。
{
/* 顶部背景色 */}
<Animated.View
style={
{
backgroundColor:this.backgroundAnimated
}}
>
...
</Animated.View>
顶部图片透明度随滑动渐变
实现原理同上,只不过将View组件替换为Image组件显示,改变的是Image组件的透明度。
//声明滑动动画事件
this.animatedEvent = Animated.event(
[
{
nativeEvent: {
contentOffset: {
y: