BÀI 7 - FLATLIST TRONG REACT NATIVE

Video bài học

  • FlatList là một cách khác dùng phổ biến hơn ScrollView trong React Native.

  • Bên dưới sẽ hướng dẫn cách tạo mảng trong state và lấy dữ liệu từ nó để đổ ra FlatList

  • Tạo state và đổ dữ liệu vào FlatList như dưới

import React from 'react';

import { FlatList, StyleSheet } from 'react-native';

import ListComponents from './Components/ListComponents';


export default class App extends React.Component {

constructor(props) {

super(props);

this.state = {

categories: [

{ id: 1, name: 'Component 1' },

{ id: 2, name: 'Component 2' },

{ id: 3, name: 'Component 3' },

{ id: 4, name: 'Component 4' },

{ id: 5, name: 'Component 5' },

{ id: 6, name: 'Component 6' }

]

}

}


render() {

const { categories } = this.state;

return (

<FlatList

data={categories}

renderItem={({ item }) => <ListComponents category={item} />}

keyExtractor={item => `${item.id}`}

contentContainerStyle = {styles.scrollView}

/>

);

}

}


const styles = StyleSheet.create({

container: {

flex: 1,

backgroundColor: '#fff',

alignItems: 'stretch',

justifyContent: 'center'

},

scrollView: {

paddingLeft: 16,

paddingRight: 16

}

});

  • Sửa tệp ListComponents như dưới

import React from "react";

import { Image, StyleSheet, Text, View } from 'react-native';

import IconImage from '../assets/icons8-user-64.png';


export default function ListComponents(props) {

const { category } = props

return (

<View style={styles.container}>

<Text style={styles.title}>{category.name}</Text>

<Image style={styles.categoryImage} source={IconImage} />

</View>

);

}


const styles = StyleSheet.create({

container: {

alignItems: 'center',

padding: 16,

borderRadius: 4,

backgroundColor: '#FFF',

// Android

elevation: 5,

// IOS

shadowColor: '#000',

shadowOpacity: 0.3,

shadowRadius: 10,

shadowOffset: { height: 0, width: 0 },

marginBottom: 16

},

categoryImage: {

height: 46,

width: 46

},

title:{

textTransform: 'uppercase',

marginBottom: 8,

fontWeight: '700'

}

})