首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Using List Views

React Native提供了一套用于呈现数据列表的组件。一般来说,你会想要使用FlatList或SectionList。

FlatList组件显示一个不断变化但具有相似结构的数据的滚动列表。FlatList对于长时间的数据列表来说效果很好,这些数据的数量可能会随着时间而改变。不像更通用的ScrollViewFlatList只能渲染当前在屏幕上显示的元素,而不是一次显示所有元素。

FlatList组件需要两个道具:datarenderItemdata是列表的信息来源。renderItem从源获取一个项目并返回一个格式化的组件进行渲染。

这个例子创建了一个简单FlatList的硬编码数据。data道具中的每个项目都被渲染为一个Text组件。该FlatListBasics组件然后呈现FlatList所有Text组件。

代码语言:javascript
复制
import React, { Component } from 'react';
import { AppRegistry, FlatList, StyleSheet, Text, View } from 'react-native';

export default class FlatListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={[
            {key: 'Devin'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FlatListBasics);

如果要将一组数据呈现为逻辑部分,也许使用部分标题(类似于UITableViewiOS 上的s),则需要使用SectionList。

代码语言:javascript
复制
import React, { Component } from 'react';
import { AppRegistry, SectionList, StyleSheet, Text, View } from 'react-native';

export default class SectionListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <SectionList
          sections={[
            {title: 'D', data: ['Devin']},
            {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  sectionHeader: {
    paddingTop: 2,
    paddingLeft: 10,
    paddingRight: 10,
    paddingBottom: 2,
    fontSize: 14,
    fontWeight: 'bold',
    backgroundColor: 'rgba(247,247,247,1.0)',
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics);

列表视图最常见的用途之一是显示从服务器获取的数据。为此,您需要了解React Native中的网络。

扫码关注腾讯云开发者

领取腾讯云代金券