我正在使用多列 FlatList
在我的 React Native 应用程序中显示如下所示的项目(左图)。我正在尝试像许多其他应用程序一样将 AdMob 横幅集成到应用程序中,并将广告横幅插入列表中间,如下图(右图)。
据我所知,FlatList 不支持这种开箱即用的布局。我想知道实现此功能并且不影响应用程序性能的好做法是什么。
(旁注,当接近列表末尾时,该列表支持下拉刷新和无限加载。)。
预先感谢您的任何建议。
最佳答案
在这种情况下,我总是建议放弃 numColumns
属性并将其替换为自定义渲染函数,该函数自行处理列。
假设我们有以下数据结构:
const DATA =
[{ id: 1, title: "Item One"}, { id: 2, title: "Item Two"}, { id: 3, title: "Item Three"},
{ id: 4, title: "Item Four"}, { id: 5, title: "Item Five"}, { id: 6, title: "Item Six"},
{ id: 7, title: "Item Seven"}, { id:8, title: "Item Eight"}, { id: 9, title: "Item Nine"},
{ id: 10, title: "Item Ten"}, { id: 11, title: "Item eleven"},
{ id: 12, title: "Item Twelve"}, { id: 13, title: "Item Thirteen"}];
正如我所说,我们不使用 numColumns 属性,而是重组我们的数据,以便我们可以按照我们想要的方式呈现我们的列表。在这种情况下,我们希望有 3 列,在 6 个项目之后,我们希望显示一个广告横幅。
数据修改:
modifyData(data) {
const numColumns = 3;
const addBannerAfterIndex = 6;
const arr = [];
var tmp = [];
data.forEach((val, index) => {
if (index % numColumns == 0 && index != 0){
arr.push(tmp);
tmp = [];
}
if (index % addBannerAfterIndex == 0 && index != 0){
arr.push([{type: 'banner'}]);
tmp = [];
}
tmp.push(val);
});
arr.push(tmp);
return arr;
}
现在我们可以渲染转换后的数据:
主要渲染函数:
render() {
const newData = this.modifyData(DATA); // here we can modify the data, this is probably not the spot where you want to trigger the modification
return (
<View style={styles.container}>
<FlatList
data={newData}
renderItem={({item, index})=> this.renderItem(item, index)}
/>
</View>
);
}
RenderItem 函数:
我删除了一些内联样式以使其更清晰。
renderItem(item, index) {
// if we have a banner item we can render it here
if (item[0].type == "banner"){
return (
<View key={index} style={{width: WIDTH-20, flexDirection: 'row'}}>
<Text style={{textAlign: 'center', color: 'white'}}> YOUR AD BANNER COMPONENT CAN BE PLACED HERE HERE </Text>
</View>
)
}
//otherwise we map over our items and render them side by side
const columns = item.map((val, idx) => {
return (
<View style={{width: WIDTH/3-20, justifyContent: 'center', backgroundColor: 'gray', height: 60, marginLeft: 10, marginRight: 10}} key={idx}>
<Text style={{textAlign: 'center'}}> {val.title} </Text>
</View>
)
});
return (
<View key={index} style={{width: WIDTH, flexDirection: 'row', marginBottom: 10}}>
{columns}
</View>
)
}
输出:
工作示例:
https://snack.expo.io/SkmTqWrJS
关于react-native - react 原生多列 FlatList 插入横幅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56607212/