5.1 使用 FlatList 实现品类页面

图5-1 品类页面 如图5-1所示,品类页面是一个列表页面,每个条目是一张图片,采用 FlatList 实现非常方便。 修改 /src/pages/CategoryPage.js 代码:

import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    FlatList,
    TouchableOpacity,
    Image,
    StatusBar,
    Platform
} from 'react-native';

import theme from '../config/theme';
import px2dp from '../utils/px2dp';

let imageResource = [require('../images/category1.png'), require('../images/category2.png'), require('../images/category3.png'), require('../images/category4.png')];

export default class CategoryPage extends Component<> {
    componentWillUnmount() {
        this._navListener.remove();
    }

    componentDidMount() {
        this._navListener = this.props.navigation.addListener('didFocus', () => {
            StatusBar.setBarStyle('dark-content');
            Platform.OS === 'android' && StatusBar.setBackgroundColor('#fff');
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <FlatList style={{flex: 1}}
                          data={imageResource}
                          renderItem={this._renderItemComponent}
                          keyExtractor={(item, index) => 'Category' + index}/>
            </View>
        );
    }
    // 渲染每个条目
    _renderItemComponent = ({item, index}) => {
        return (
            <View style={{backgroundColor: '#fff', paddingVertical: px2dp(12), alignItems: 'center'}}>
                <TouchableOpacity onPress={this._onItemPress.bind(this,index)}>
                    <Image source={item}/>
                </TouchableOpacity>
            </View>
        )
    };
    // 条目的点击事件
    _onItemPress(index) {
        console.log(index)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.lightGray,
        paddingTop: px2dp(1)
    }
});

上面的代码列举了 FlatList 必要的几个属性:

  • data 设置列表显示的数据源,接收数组格式的数据,数组中的每个元素对应列表的每个条目;
  • renderItem 该属性值是一个函数,定义了如何渲染其中一个条目,函数具有 item 和 index, 其中 item 就是数据源数组中的元素,index 对应元素在数组中的位置;
  • keyExtractor 该属性定义了每一个条目的唯一标识。

如果你已经从 GitHub 上克隆了这个程序的 Git 仓库,那么可以执行 git checkout 5a 签出程序的这个版本。

results matching ""

    No results matching ""