123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
import * as React from 'react';import { StyleSheet, Animated } from "react-native";/** * 滑动吸顶效果组件 * @export * @class StickyHeader */export default class StickyHeader extends React.Component{ static defaultProps = { stickyHeaderY: -1, stickyScrollY: new Animated.Value(0) } constructor(props) { super(props); this.state = { 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 ( <Animated.View onLayout= { this._onLayout } style = { [ style, styles.container, { transform: [{ translateY }] } ]} > { children } </Animated.View> ) }}const styles = StyleSheet.create({ container: { zIndex: 100 },});
1234567891011121314151617181920212223242526272829303132333435363738
this.state = { scrollY: new Animated.Value(0), headHeight:-1};<Animated.ScrollView style={{ flex: 1 }} onScroll={ Animated.event( [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } // 记录滑动距离 }], { useNativeDriver: true }) // 使用原生动画驱动 } scrollEventThrottle={1}> <View onLayout={(e) => { let { height } = e.nativeEvent.layout; this.setState({ headHeight: height }); // 给头部高度赋值 }}> // 里面放入第一部分组件 </View> <StickyHeader stickyHeaderY={this.state.headHeight} // 把头部高度传入 stickyScrollY={this.state.scrollY} // 把滑动距离传入 > // 里面放入第二部分组件 </StickyHeader> // 这是第三部分的列表组件 <FlatList data={this.state.dataSource} renderItem={({item}) => this._createListItem(item)} /> </Animated.ScrollView>
react-native 滑动吸顶效果
有好货
react-native 列表吸顶效果&滑动渐变动画&轮播渐变动画