如何在 React Native 中使用 FlatList 显示数据? [英] How to display data using FlatList in react native?

查看:35
本文介绍了如何在 React Native 中使用 FlatList 显示数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了 cardView,但如何将其转换为 <FlatList/> 我无法理解 FlatList 的 renderItem 应该是什么 ?

I have created cardView but how can I convert it to <FlatList/> I am not able to understand what should be the renderItem of FlatList ?

我当前的代码:

<ScrollView style={styles.container}>
                <View style={styles.cardView}>
                    <Text style={styles.projectName}>{marketing_updates.length != 0 ? marketing_updates[0].project_name: ""}</Text>
                    <Text style={styles.title}>{marketing_updates.length != 0 ? marketing_updates[0].title: ""}</Text>
                    <Text style={styles.description}>Description: {marketing_updates.length != 0 ? marketing_updates[0].description: ""}</Text>
                    <Image
                    style={styles.img}
                    source={{uri: marketing_updates.length != 0 ? marketing_updates[0].image: null}}
                    />
                    <View style={styles.buttons}>
                        <Text style={styles.like}>Like</Text>
                        <Text style={styles.share}>Share</Text>
                    </View>
                    <View style={styles.comment}>
                        <Text>Comments: </Text>
                        <Text>comment 1</Text>
                        <Text>comment 2</Text>
                        <Text>comment 3</Text>
                    </View>
                </View>

            </ScrollView>

如何将其转换为 FlatList ?

How can I convert it to FlatList ?

我尝试了什么:

<ScrollView style={styles.container}>
                <FlatList
                data={marketing_updates.length != 0 && marketing_updates ? marketing_updates : null}
                renderItem={}
                />

            </ScrollView>

我无法理解 renderItem={} 里面应该有什么?

I am not able to understand what should be there inside renderItem={} ?

推荐答案

renderItem 接受一个函数,该函数将当前列表项作为参数并渲染一个组件.您可以将其视为地图"函数,就像 listItems.map(item => <MyListItem {...item}/>.

renderItem accepts a function which takes the current list item as an argument and renders a component. You can think of it as the "map" function like in listItems.map(item => <MyListItem {...item} />.

我建议您创建一个展示性的卡片"组件来封装视图渲染逻辑(例如 MarketingUpdateCard),并将列表项数据作为道具传递:

I'd recommend you create a presentational "card" component to encapsulate the view rendering logic (e.g. MarketingUpdateCard) and just pass the list item data as props:

renderItem={({ item }) => (
  <MarketingUpdateCard {...item} />
)}

以及一个示例卡片组件:

And an example card component:

// MarketingUpdateCard.js
const MarketingUpdateCard = ({ project_name, title, description, image }) => (
    <View>
      // your current card template here
    </View>
)

这篇关于如何在 React Native 中使用 FlatList 显示数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆