All*_*ang 5 react-native react-native-flatlist
我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"}];
Run Code Online (Sandbox Code Playgroud)
正如我说的,我们不使用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;
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以渲染转换后的数据:
主要渲染功能:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
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>
)
}
Run Code Online (Sandbox Code Playgroud)
输出:
工作示例:
https://snack.expo.io/SkmTqWrJS
| 归档时间: |
|
| 查看次数: |
489 次 |
| 最近记录: |