RN FlatList使用

FlatList類似於Android中的ListView或者RecyclerView,主要用於列表的繪製,允許橫向或縱向滾動的滑動控件,使用也不像ListView或者RecyclerView那樣複雜。

1.一個基礎的FlatList控件:

                <FlatList
                    style={styles.container}
                    data={this.state.dataSource}
                    renderItem={({item}) => this._createListItem(item)}
                />

data類似於Android中的數據源,比如List<String> mData這樣的數組或者集合。

2.繪製Item:


    /**
     * 創建佈局
     */
    _createListItem(item) {
        return (
            <TouchableOpacity activeOpacity={0.5} onPress={() => this._onItemClick(item)}>
                <View style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    // justifyContent: 'center',
                    marginTop: 5,
                    backgroundColor: '#fff',
                    padding: 10
                }}>
                    <Image source={{uri: item.logo_url}} style={styles.itemImages}/>
                    <Text style={{marginLeft: 6}}>
                        {item.baike_name}
                    </Text>
                </View>
            </TouchableOpacity>
        );
    }

這裏就是繪製Item的佈局,以及賦值操作,類似於Android的Adapter所做的事。

3.FlatList常用屬性:

                <FlatList
                    style={styles.container}
                    data={this.state.dataSource}
                    //item顯示的佈局
                    renderItem={({item}) => this._createListItem(item)}
                    // 空佈局
                    ListEmptyComponent={this._createEmptyView}
                    //添加頭尾佈局
                    ListHeaderComponent={this._createListHeader}
                    // ListFooterComponent={this._createListFooter}
                    ListFooterComponent={this._createListFooter.bind(this)}
                    //下拉刷新相關
                    //onRefresh={() => this._onRefresh()}
                    refreshControl={
                        <RefreshControl
                            title={'Loading'}
                            colors={['red']}
                            refreshing={this.state.isRefresh}
                            onRefresh={() => {
                                this._onRefresh();
                            }}
                        />
                    }
                    refreshing={this.state.isRefresh}
                    //加載更多
                    onEndReached={() => this._onLoadMore()}
                    onEndReachedThreshold={0.1}
                    ItemSeparatorComponent={this._separator}
                    keyExtractor={this._extraUniqueKey}
                />

4.分割線:

    /**
     * 分割線
     */
    _separator() {
        return <View style={{height: 1, backgroundColor: '#999999'}}/>;
    }

5.Header頭:

    /**
     * 創建頭部佈局
     */
    _createListHeader() {
        return (
            <View style={styles.headView}>
                <Text style={{color: 'white'}}>
                    頭部佈局
                </Text>
            </View>
        )
    }

6.Footer尾:

    /**
     * 創建尾部佈局
     */
    _createListFooter = () => {
        return (
            <View style={styles.footerView}>
                {this.state.showFoot === 1 && <ActivityIndicator/>}
                <Text style={{color: 'red'}}>
                    {this.state.showFoot === 1 ? '正在加載更多數據...' : '沒有更多數據了'}
                </Text>
            </View>
        )
    }

7.EmptyView空視圖:

    /**
     * 空佈局
     */
    _createEmptyView() {
        return (
            <View style={{height: '100%', alignItems: 'center', justifyContent: 'center'}}>
                <Text style={{fontSize: 16}}>
                    暫無列表數據,下啦刷新
                </Text>
            </View>
        );
    }

8.下拉刷新以及上拉加載:

    /**
     * 下啦刷新
     * @private
     */
    _onRefresh = () => {
        // 不處於 下拉刷新
        if (!this.state.isRefresh) {
            this.page = 1
            this._getHotList()
        }
    };

    /**
     * 加載更多
     * @private
     */
    _onLoadMore() {
        // 不處於正在加載更多 && 有下拉刷新過,因爲沒數據的時候 會觸發加載
        if (!this.state.isLoadMore && this.state.dataSource.length > 0 && this.state.showFoot !== 2) {
            this.page = this.page + 1
            this._getHotList()
        }
    }

9.Item點擊事件:

    /**
     * item點擊事件
     */
    _onItemClick(item) {
        console.log("page" + this.state.page + " = " + item.baike_name)
    }

10.Item綁定key抑制警告:

    _extraUniqueKey(item, index) {
        return "index" + index + item;
    }

完整代碼:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
    ActivityIndicator,
    FlatList,
    Image,
    RefreshControl,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
//屏幕信息
const dimensions = require('Dimensions');
//獲取屏幕的寬度和高度
const {width, height} = dimensions.get('window');


export default class App extends Component {

    constructor(props) {
        super(props);
        //當前頁
        this.page = 1
        //狀態
        this.state = {
            // 列表數據結構
            dataSource: [],
            // 下拉刷新
            isRefresh: false,
            // 加載更多
            isLoadMore: false,
            // 控制foot  1:正在加載   2 :無更多數據
            showFoot: 1,
        }
    }

    /**
     * 獲取360 下載列表
     * @private
     */
    _getHotList() {
        this.state.isLoadMore = true
        fetch("http://m.app.haosou.com/index/getData?type=1&page=" + this.page)
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson)
                if (this.page === 1) {
                    console.log("重新加載")
                    this.setState({
                        isLoadMore: false,
                        dataSource: responseJson.list
                    })
                } else {
                    console.log("加載更多")
                    this.setState({
                        isLoadMore: false,
                        // 數據源刷新 add
                        dataSource: this.state.dataSource.concat(responseJson.list)
                    })
                    if (this.page <= 3) {
                        this.setState({
                            showFoot: 1
                        })
                    } else if (this.page > 3) {
                        this.setState({
                            showFoot: 2
                        })
                    }
                }


            })
            .catch((error) => {
                console.error(error);
            });
    }

    render() {
        return (
            <View style={styles.container}>
                <FlatList
                    style={styles.container}
                    data={this.state.dataSource}
                    //item顯示的佈局
                    renderItem={({item}) => this._createListItem(item)}
                    // 空佈局
                    ListEmptyComponent={this._createEmptyView}
                    //添加頭尾佈局
                    ListHeaderComponent={this._createListHeader}
                    // ListFooterComponent={this._createListFooter}
                    ListFooterComponent={this._createListFooter.bind(this)}
                    //下拉刷新相關
                    //onRefresh={() => this._onRefresh()}
                    refreshControl={
                        <RefreshControl
                            title={'Loading'}
                            colors={['red']}
                            refreshing={this.state.isRefresh}
                            onRefresh={() => {
                                this._onRefresh();
                            }}
                        />
                    }
                    refreshing={this.state.isRefresh}
                    //加載更多
                    onEndReached={() => this._onLoadMore()}
                    onEndReachedThreshold={0.1}
                    ItemSeparatorComponent={this._separator}
                    keyExtractor={this._extraUniqueKey}
                />
            </View>
        );
    }

    _extraUniqueKey(item, index) {
        return "index" + index + item;
    }

    /**
     * 分割線
     */
    _separator() {
        return <View style={{height: 1, backgroundColor: '#999999'}}/>;
    }

    /**
     * 創建頭部佈局
     */
    _createListHeader() {
        return (
            <View style={styles.headView}>
                <Text style={{color: 'white'}}>
                    頭部佈局
                </Text>
            </View>
        )
    }

    /**
     * 創建尾部佈局
     */
    _createListFooter = () => {
        return (
            <View style={styles.footerView}>
                {this.state.showFoot === 1 && <ActivityIndicator/>}
                <Text style={{color: 'red'}}>
                    {this.state.showFoot === 1 ? '正在加載更多數據...' : '沒有更多數據了'}
                </Text>
            </View>
        )
    }


    /**
     * 創建佈局
     */
    _createListItem(item) {
        return (
            <TouchableOpacity activeOpacity={0.5} onPress={() => this._onItemClick(item)}>
                <View style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    // justifyContent: 'center',
                    marginTop: 5,
                    backgroundColor: '#fff',
                    padding: 10
                }}>
                    <Image source={{uri: item.logo_url}} style={styles.itemImages}/>
                    <Text style={{marginLeft: 6}}>
                        {item.baike_name}
                    </Text>
                </View>
            </TouchableOpacity>
        );
    }

    /**
     * 空佈局
     */
    _createEmptyView() {
        return (
            <View style={{height: '100%', alignItems: 'center', justifyContent: 'center'}}>
                <Text style={{fontSize: 16}}>
                    暫無列表數據,下啦刷新
                </Text>
            </View>
        );
    }

    /**
     * 下啦刷新
     * @private
     */
    _onRefresh = () => {
        // 不處於 下拉刷新
        if (!this.state.isRefresh) {
            this.page = 1
            this._getHotList()
        }
    };

    /**
     * 加載更多
     * @private
     */
    _onLoadMore() {
        // 不處於正在加載更多 && 有下拉刷新過,因爲沒數據的時候 會觸發加載
        if (!this.state.isLoadMore && this.state.dataSource.length > 0 && this.state.showFoot !== 2) {
            this.page = this.page + 1
            this._getHotList()
        }
    }

    /**
     * item點擊事件
     */
    _onItemClick(item) {
        console.log("page" + this.state.page + " = " + item.baike_name)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    headView: {
        width: width,
        height: 50,
        backgroundColor: 'red',
        justifyContent: 'center',
        alignItems: 'center'
    },
    footerView: {
        flexDirection: 'row',
        width: width,
        height: 50,
        //backgroundColor: 'red',
        justifyContent: 'center',
        alignItems: 'center'
    },
    itemImages: {
        width: 60,
        height: 60,
        resizeMode: 'stretch'
    },
});

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章