React Native - 可滚动视图 (ScrollView)
React Native - ScrollView
Section titled “React Native - ScrollView”ScrollView 组件是一个通用的滚动容器,可以容纳多个组件和视图。它适用于显示少量不同类型的项目,或者当内容可能超出屏幕大小时。对于大量相似数据的长列表,通常使用 FlatList 性能会更好。
本章将演示如何使用 ScrollView 使内容可滚动。
ScrollView 基本示例
Section titled “ScrollView 基本示例”我们将创建一个包含多个 Text 元素的 ScrollView,使内容可以垂直滚动。
MyScrollView.js
import React from 'react';import { ScrollView, Text, View, StyleSheet, StatusBar } from 'react-native';
const MyScrollView = () => { const items = [ { id: '1', text: 'Item 1: Lorem ipsum dolor sit amet.' }, { id: '2', text: 'Item 2: Consectetur adipiscing elit.' }, { id: '3', text: 'Item 3: Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' }, { id: '4', text: 'Item 4: Ut enim ad minim veniam, quis nostrud exercitation.' }, { id: '5', text: 'Item 5: Ullamco laboris nisi ut aliquip ex ea commodo consequat.' }, { id: '6', text: 'Item 6: Duis aute irure dolor in reprehenderit.' }, { id: '7', text: 'Item 7: In voluptate velit esse cillum dolore eu fugiat nulla pariatur.' }, { id: '8', text: 'Item 8: Excepteur sint occaecat cupidatat non proident.' }, { id: '9', text: 'Item 9: Sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { id: '10', text: 'This is the tenth item in the scrollable list.' }, { id: '11', text: 'Adding more items to ensure scrolling is needed.' }, { id: '12', text: 'The ScrollView will allow vertical scrolling.' }, ];
return ( <View style={styles.safeArea}> <StatusBar barStyle="dark-content" /> <ScrollView style={styles.scrollView} // contentContainerStyle={styles.contentContainer} // Optional: style the inner content container // keyboardShouldPersistTaps='handled' // Useful for forms inside ScrollView // showsVerticalScrollIndicator={false} // To hide the scrollbar > <Text style={styles.title}>Scrollable Content</Text> {items.map((item) => ( <View key={item.id} style={styles.itemContainer}> <Text style={styles.itemText}>{item.text}</Text> </View> ))} </ScrollView> </View> );};
const styles = StyleSheet.create({ safeArea: { flex: 1, // paddingTop: StatusBar.currentHeight, // Only for Android if not using SafeAreaView }, scrollView: { backgroundColor: '#f0f8ff', }, contentContainer: { // Example style for the inner content view paddingBottom: 20, // Ensure space at the bottom }, title: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', marginVertical: 20, color: '#333', }, itemContainer: { backgroundColor: '#ffffff', padding: 15, marginVertical: 8, marginHorizontal: 16, borderRadius: 8, borderWidth: 1, borderColor: '#e0e0e0', }, itemText: { fontSize: 16, color: '#555', },});
export default MyScrollView;- 包裹内容:
ScrollView的所有子组件都会被渲染,即使它们当前不在屏幕上可见。这就是为什么对于长列表推荐使用FlatList的原因。 - 垂直滚动:默认情况下,
ScrollView会垂直滚动。要启用水平滚动,请设置horizontal={true}属性 (prop)。 - 样式:你可以为
ScrollView本身设置样式(例如backgroundColor),也可以使用contentContainerStyle属性为内部内容容器设置样式(例如,为内容周围添加内边距)。 keyboardShouldPersistTaps:控制当焦点不在文本输入框内时,点击是否会隐藏键盘。'handled'通常是一个不错的默认值。
当你运行此组件时,会看到一个项目列表。如果所有项目的总高度超出了屏幕高度,你将可以垂直滚动来查看所有内容。
水平 ScrollView
Section titled “水平 ScrollView”要创建水平 ScrollView,添加 horizontal={true} 属性 (prop)。你可能还需要设置子元素的样式,使其按行排列(例如,在容器上使用 flexDirection: 'row',或者依靠其自然的内联流)。
// Inside your render method for a horizontal scroll:// <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>// <View style={styles.horizontalItem}><Text>Item 1</Text></View>// <View style={styles.horizontalItem}><Text>Item 2</Text></View>// {/* ... more items ... */}// </ScrollView>
// const styles = StyleSheet.create({// horizontalItem: {// width: 150, // Example fixed width for horizontal items// height: 100,// backgroundColor: 'skyblue',// marginHorizontal: 10,// justifyContent: 'center',// alignItems: 'center',// }// });ScrollView 与 FlatList 的比较
Section titled “ScrollView 与 FlatList 的比较”- 在以下情况使用
ScrollView:- 内容量较少且类型混合。
- 需要一个通用的滚动容器来容纳各种视图,而不是统一数据结构的列表。
- 在以下情况使用
FlatList:- 数据列表很长(成百上千个项目)。
- 项目结构基本一致。
- 需要性能优化,如项目虚拟化、下拉刷新或无限滚动。
选择正确的组件对于确保良好的性能和用户体验至关重要。有关 ScrollView 的属性和更多用法详情,请参阅官方文档:https://reactnative.dev/docs/scrollview