我有两个数组,一个用于产品,一个用于主管。显然,两者都有非常不同类型的数据。我想创建一个可滚动列表,该列表将使用单个滚动列表显示所有产品,然后是所有主管。这可能与 React Native 的 FlatList 一起使用吗?如果是这样,或者如果不是,我该怎么做?
我目前可以按如下方式呈现单个数据数组:
<FlatList
data={this.state.products}
renderItem={this.renderItem}
/>
但是,如何将主管数据附加到此列表的末尾?显然,因为两个数组之间的数据完全不同,我不能简单地合并数组和/或相同的 renderItem 函数。
如何在同一个可滚动列表中一个接一个地显示两种完全不同类型的数据?
最佳答案
您可以将数据合并在一起,并使用单个 FlatList 和单个 renderItem Prop 。如果没有您的数据样本,这有点像猜谜游戏,但下面是您可以如何做的示例。
示例
假设您有如下数据结构。
const Products = [
{
id: 1,
name: 'Product 1'
},
{
id: 2,
name: 'Product 2'
},
{
id: 3,
name: 'Product 3'
},
{
id: 4,
name: 'Product 4'
},
];
const Supervisors = [
{
belongsToPruduct: 1,
name: 'SuperVisor 1'
},
{
belongsToPruduct: 3,
name: 'SuperVisor 2'
},
{
belongsToPruduct: 2,
name: 'SuperVisor 3'
},
{
belongsToPruduct: 4,
name: 'SuperVisor 4'
}
];
假设您在
Products
中渲染 FlatList
。您可以在 renderItem
函数中执行以下操作renderItem = ({ item }) => {
const superviors = Supervisors.filter((supervisor) => supervisor.belongsToPruduct === item.id)
return (
<View style={styles.productContainer}>
<Text style={styles.productName}>{item.name}</Text>
<View style={styles.supervisorsContainer}>
{
superviors.map((supervisor) => <Text style={styles.supervisorName}>{supervisor.name}</Text>)
}
</View>
</View>
)
}
更新
引用您的评论,我认为您可以使用
SectionList
而不是 FlatList
<SectionList
renderSectionHeader={({ section: { title } }) => <Text style={{ fontWeight: 'bold' }}>{title}</Text>}
sections={[
{ title: 'Products', data: Products, renderItem: ({ item, index, section: { title, data } }) => <Text>{item.name}</Text> },
{ title: 'Supervisors', data: Supervisors, renderItem: ({ item, index, section: { title, data } }) => <Text>{item.name}</Text>},
]}
keyExtractor={(item, index) => item.name + index}
/>
关于react-native - 使用带有两个完全不同的数据数组的 React Native FlatList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084275/