阅读量:0
在ScrollView组件里面把第一元素固定在视图顶部的效果,ScrollView在手机上自带了bounce回弹的效果,不管内容是不是超出组件高度还是宽度
实现效果
代码实现
import { View, Text, StyleSheet, Dimensions, TextInput, Button, Alert, ScrollView, StatusBar, SafeAreaView, } from 'react-native'; function HomeScreen() { const handleStart = () => { // Alert.alert('Scroll started'); }; const handleEnd = () => { // Alert.alert('Scroll ended'); }; const handleTop = () => { Alert.alert('Scrolled to top'); }; return ( <SafeAreaView style={styles.container}> <ScrollView style={styles.scrollView} onMomentumScrollBegin={handleStart} onMomentumScrollEnd={handleEnd} stickyHeaderIndices={[0]} onScrollToTop={handleTop}> <View> <Text style={styles.title}>这是一个标题</Text> </View> <Text style={styles.text}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </Text> </ScrollView> </SafeAreaView> ); } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: StatusBar.currentHeight - 40, }, title: { fontSize: 22, backgroundColor: 'red', height: 40, color: '#fff', textAlign: 'center', }, scrollView: { backgroundColor: 'pink', marginHorizontal: 10, }, text: { fontSize: 42, }, }); export default HomeScreen;
注意
- 本例子是要把文字固定在顶部,必须在Text组件外面再包一层View组件,否则Text里面的样式会失效。
showsVerticalScrollIndicator={false}
隐藏滚动条,对应的还有水平方向的- view和safeview的差别