【react-native】滑动吸顶效果 + 下拉刷新

现象:最近开发RN项目,需要开发一个页面滑动过程中的tab吸顶的效果。

解决方案: 使用Animated创建动画

具体代码如下:

  1. index.tsx
import React, { Component } from 'react'

import { View, Text, ViewStyle, StyleSheet, ImageBackground, Animated, RefreshControl } from 'react-native'
import StickyHeader from "./StickyHeader"
import { images, dimensions } from '../../../../res'

interface IState {
  refreshing: boolean,
  scrollHeight: number,
  scrollY: Animated.Value
}

export class PrivateCollectScreen extends Component {

  readonly state: IState = {
    scrollY: new Animated.Value(0),
    scrollHeight: -1,
    refreshing: false
  }



  render() {
    return (
      
         { // 再刷新时调用
                this.setState({ refreshing: true })
              }} />
          }
        >


           {
            this.setState({ scrollHeight: e.nativeEvent.layout.height }) // 获取头部的高度
          }}>
            
              {/* 头部内容 */}
            
          


          
            
              固定栏
            
          


          {/* 底部内容 */}
          {
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((item, index) => {
              return (底部内容{index})
            })
          }
        
      
    )
  }
}

interface Styles {
  container: ViewStyle
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  }
})
  1. StickyHeader.tsx
import * as React from 'react'
import { StyleSheet, Animated } from 'react-native'

interface IState {
  stickyLayoutY: number,
  stickyHeaderY: number,
  stickyScrollY: Animated.Value
}

/**
 * 滑动吸顶效果组件
 * @export
 * @class StickyHeader
 */
export default class StickyHeader extends React.Component {


  readonly state: IState = {
    stickyHeaderY: -1,
    stickyScrollY: new Animated.Value(0),
    stickyLayoutY: 0
  }
  // 兼容代码,防止没有传头部高度
  _onLayout = (event) => {
    this.setState({
      stickyLayoutY: event.nativeEvent.layout.y,
    })
  }

  render() {
    const { stickyHeaderY, stickyScrollY, children, style } = this.props
    const { stickyLayoutY } = this.state
    let y = stickyHeaderY !== -1 ? stickyHeaderY : stickyLayoutY
    const translateY = stickyScrollY.interpolate({
      inputRange: [-1, 0, y, y + 1],
      outputRange: [0, 0, 0, 1],
    })

    return (
      
        {children}
      
    )
  }
}

const styles = StyleSheet.create({
  container: {
    zIndex: 100
  }
})
  1. 效果图


    效果图

你可能感兴趣的:(【react-native】滑动吸顶效果 + 下拉刷新)