一、使用 scrollView 实现

1)stickyHeader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
},
});

2)使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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>

二、使用 sectionList 实现

react-native 滑动吸顶效果

有好货

react-native 列表吸顶效果&滑动渐变动画&轮播渐变动画