天天看點

FlatList使用示例包含RefreshControlFlatList屬性介紹RefreshControl屬性介紹代碼

FlatList使用示例包含RefreshControl

  • FlatList屬性介紹
  • RefreshControl屬性介紹
  • 代碼

FlatList屬性介紹

  • ItemSeparatorComponent:分割線元件,
  • ListFooterComponent:結尾元件
  • ListHeaderComponent:頭元件
  • data:清單資料
  • horizontal:設定為true則變為水準清單。
  • numColumns:列數 元件内元素必須是等高的,無法支援瀑布流布局
  • columnWrapperStyle:numColumns大于1時,設定每行的樣式
  • getItemLayout:如果我們知道行高可以用此方法節省動态計算行高的開銷。
  • refreshing:是否正在加載資料
  • onRefresh:設定此屬性需要一個标準的 RefreshControl 控件,重新整理資料
  • renderItem:渲染每個元件
  • onViewableItemsChanged:當一個新的Item渲染或者隐藏 的時候調用此方法。參數:info: {viewableItems: Array, changed: Array}
  • viewableItems:目前可見的Item,changed:渲染或者隐藏的Item。
  • scrollToEnd({params?: ?{animated?: ?boolean}}):滾動到末尾,如果不設定getItemLayout屬性的話,可能會比較卡。
  • scrollToIndexparams: {animated?: ?boolean, index: number, viewPosition?: number}:滾動到制定的位置
  • scrollToOffset(params: {animated?: ?boolean, offset: number}):滾動到指定的偏移的位置。

RefreshControl屬性介紹

  • onRefresh:開始重新整理時調用
  • refreshing:設定為true顯示訓示器,false:隐藏。
  • colors(android):訓示器顔色,可以多個,循環顯示。
  • progressBackgroundColor(android):訓示器背景顔色
  • size(android):值:[0,1]。訓示器大小,預設1,0:large
  • progressViewOffset(android):訓示器距離頂部的位置,預設0.
  • tintColor(ios):訓示器顔色
  • title(ios):訓示器下顯示的文字
  • titleColor(ios):訓示器下顯示的文字的顔色

代碼

import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    FlatList,
    Text,
    Button,
    ActivityIndicator,
    RefreshControl,
} from 'react-native';

const ITEM_HEIGHT = 100;

export default class FlatListDemo extends Component {
    _flatList;

    constructor(props) {
        super(props);
        this.state = {
            isRefreshing: false,
            isLoading: false,
            data: ['北京', '上海', '廣州', '深圳', '杭州', '蘇州', '成都', '武漢', '鄭州', '洛陽', '廈門', '青島', '拉薩'],
        };
    }

    _renderItem = (item) => {
        // 此處item的資料結構是{item:對應data數組中的每一項,index:data數組中每一項的下标,separators:{}}
        // console.warn(item);
        const txt = `第${item.index}個` + ` title=${item.item}`;
        const bgColor = item.index % 2 === 0 ? 'red' : 'blue';
        return <Text style={[
            { flex: 1, height: ITEM_HEIGHT, backgroundColor: bgColor },
            styles.txt,
        ]} key={item.index}>{txt}</Text>;
    }

    _header = () => <Text style={[styles.txt, { backgroundColor: 'black' }]}>這是頭部</Text>

    _footer = () => <Text style={[styles.txt, { backgroundColor: 'black' }]}>這是尾部</Text>

    _separator = () => <View style={{ height: 2, backgroundColor: 'yellow' }}/>

    genIndicator = () => (this.state.isLoading && <View style={styles.indicatorContainer}>
        <ActivityIndicator
            style={styles.indicator}
            size='large'
            animating={true}
        />
        <Text style={{ textAlign: 'center' }}>正在加載更多</Text>
    </View>)

    loadData = () => {
        if (this.state.isLoading) return;
        this.setState({
            isLoading: true,
        });
        setTimeout(() => {
            this.setState({
                data: this.state.data.concat(1),
                isLoading: false,
            });
        }, 2000);
    }

    refreshData = () => {
        if (this.state.isLoading || this.state.isRefreshing) return;
        this.setState({ isRefreshing: true });
        setTimeout(() => {
            const newAry = this.state.data;
            newAry.unshift(1);
            this.setState({
                data: newAry,
                isRefreshing: false,
            });
        }, 2000);
    }

    _keyExtractor = (item, index) => {
        console.log(`${item}${index}`);
        return `${item}${index}`;
    }

    render() {
        // 根據data不同的指派情況檢視_renderItem中的item的值的結構
        // const data = ['北京', '上海', '廣州', '深圳', '杭州', '蘇州', '成都', '武漢', '鄭州', '洛陽', '廈門', '青島', '拉薩'];
        // for (let i = 0; i < 10; i++) {
        //     data.push({ key: i, title: `${i}` });
        // }

        const { data } = this.state;

        return (
            <View style={{ flex: 1 }}>
                <Button title='滾動到指定位置' onPress={() => {
                    // this._flatList.scrollToEnd();
                    // this._flatList.scrollToIndex({ viewPosition: 0, index: 1 });
                    this._flatList.scrollToOffset({ animated: true, offset: 200 });
                }}/>
                <View style={{ flex: 1 }}>
                    <FlatList
                        ref={flatList => this._flatList = flatList}

                        // // 設定元件頭部
                        // ListHeaderComponent={this._header}

                        // 設定元件尾部,可以在尾部元件中定義上拉重新整理的元件
                        // ListFooterComponent={this._footer}
                        ListFooterComponent={this.genIndicator}

                        // 設定元件分割線
                        ItemSeparatorComponent={this._separator}

                        // 根據data中的每項資料進行渲染
                        renderItem={this._renderItem}

                        // // 列數 元件内元素必須是等高的,無法支援瀑布流布局
                        // numColumns ={2}

                        // // numColumns大于1時,設定每行的樣式
                        // columnWrapperStyle={{
                        //     borderWidth: 20,
                        //     borderColor: 'pink',
                        //     paddingLeft: 0,
                        // }}

                        // // 設定為true則變為水準清單
                        // horizontal={true}

                        // // 如果我們知道行高可以用此方法節省動态計算行高的開銷,是一個可選的優化,注意如果你指定了SeparatorComponent,請把分隔線的尺寸也考慮到offset的計算之中。并且設定getItemLayout屬性的話在滾動清單時不會卡頓
                        getItemLayout={(data, index) => (
                            { length: ITEM_HEIGHT, offset: (ITEM_HEIGHT + 2) * index, index }
                        )}

                        // // 當清單被滾動到距離内容最底部不足onEndReachedThreshold的距離時進行滾動加載調用onEndReached這個回調。注意此參數是一個比值而非像素機關。比如,0.5表示距離内容最底部的距離為目前清單可見長度的一半時觸發。
                        // onEndReachedThreshold={1}
                        // onEndReached={(info) => {
                        //     // info:{distanceFromEnd:距離底部的距離}
                        //     // console.log(info);
                        //     // console.warn(info.distanceFromEnd);
                        //     this.loadData();
                        // }}

                        // 是否正在加載資料,在等待加載新資料時将此屬性設為true,清單就會顯示出一個正在加載的符号
                        refreshing={this.state.isRefreshing}

                        // 設定此屬性需要一個标準的 RefreshControl 控件,重新整理資料
                        onRefresh={() => {
                            this.refreshData();
                        }}
                        refreshControl={
                            <RefreshControl
                                progressBackgroundColor='pink'
                                refreshing={this.state.isRefreshing}
                                onRefresh={() => this.refreshData()}
                                tintColor="#ff0000"
                                title="Loading..."
                                titleColor="#00ff00"
                                size={0}
                                progressViewOffset={30}
                                colors={['#0000ff', '#ff0000', '#00ff00']}
                            />}

                        // onViewableItemsChanged={(info) => {
                        //     console.warn(info);
                        // }}

                        keyExtractor={this._keyExtractor}

                        // 清單資料
                        data={data}>
                    </FlatList>
                </View>

            </View>
        );
    }
}

const styles = StyleSheet.create({
    txt: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: 'white',
        fontSize: 30,
    },
    indicator: {
        color: 'red',
        margin: 10,
    },
});
           

繼續閱讀