javascript - 如何在 React Native 中使用 FlatList 显示数据?

标签 javascript reactjs react-native

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

我试过的:

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

            </ScrollView>

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

最佳答案

renderItem接受一个函数,该函数将当前列表项作为参数并呈现一个组件。您可以将其视为 listItems.map(item => <MyListItem {...item} /> 中的“ map ”功能。 .

我建议您创建一个展示性“卡片”组件来封装 View 渲染逻辑(例如 MarketingUpdateCard),并将列表项数据作为 Prop 传递:

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

还有一个示例卡片组件:

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

关于javascript - 如何在 React Native 中使用 FlatList 显示数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52589997/

相关文章:

javascript - 如何在不重复上一首歌曲的情况下随机循环播放歌曲列表? (JavaScript)

javascript - 为什么过滤字典上的 `ng-repeat` 会导致 `10 $digest() iterations reached` 错误?

javascript - Webpack: npm start "Module not found: Error: Can' t resolve ..."移动 webpack/react 文件的位置后

reactjs - 在构造函数中定义状态更好还是使用属性初始值设定项更好?

javascript - 无法更改 <SideNav> 的背景颜色

javascript - Handlebars 动态字段名称

javascript - 为动态子项添加唯一键,而无需任何唯一键

react-native - React Navigation 使用 Redux 重置堆栈的正确方法

javascript - react-native-modalbox 卡在子组件上下文中

xml - 如何在 React Native ( JavaScript ) 中创建 XML 文档?