react-native中使用長列表


React Native 提供了幾個適用於展示長列表數據的組件,一般而言我們會選用FlatList或是SectionList。
FlatList組件用於顯示一個垂直的滾動列表,其中的元素之間結構近似而僅數據不同。
FlatList更適於長列表數據,且元素個數可以增刪。和ScrollView不同的是,
FlatList並不立即渲染所有元素,而是優先渲染屏幕上可見的元素。
FlatList組件必須的兩個屬性是data和renderItem。data是列表的數據源,
而renderItem則從數據源中逐個解析數據,然后返回一個設定好格式的組件來渲染。
下面的例子創建了一個簡單的FlatList,並預設了一些模擬數據。首先是初始化FlatList所需的data,
其中的每一項(行)數據之后都在renderItem中被渲染成了Text組件,最后構成整個FlatList。

import React, { Component } from 'react';
import { 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: 'meme' },
            {key: 'dimple'},
            {key: 'smart'},
            {key: 'girl'},
            {key: 'tomy'},
            {key: 'baby' },
            {key: 'saysys'},
            {key: 'moon'}
          ]}
          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,
  },
})


如果要渲染的是一組需要分組的數據,也許還帶有分組標簽的,那么SectionList將是個不錯的選擇

import React, { Component } from 'react';
import { 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: ['dimple','girl','smart','beauty','smile']}
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
          keyExtractor={(item, index) => index}
        />
      </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
  }
})


關於keyExtractor: (item: ItemT, index: number) => string #
此函數用於為給定的item生成一個不重復的key。Key的作用是使React能夠區分同類元素的不同個體,以便在刷新時能夠確定其變化的位置
,減少重新渲染的開銷。若不指定此函數,則默認抽取item.key作為key值。若item.key也不存在,則使用數組下標。
相當於react dom循環時 用來進行diff算法的key值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM