我正在使用 FlatList 在我的应用程序中显示我的卡片组件。
我想在列表中的特定数量的卡片之后显示另一个组件(如广告或公告组件)。
作为说明,它应该如下所示;
- 卡片项目
- 卡片项目
- 卡片项目
- 卡片项目
-零件-
- 卡片项目
- 卡片项目
- 卡片项目
- 卡片项目
-零件-
...继续...
..
我正在使用 FlatList 在我的应用程序中显示我的卡片组件。
我想在列表中的特定数量的卡片之后显示另一个组件(如广告或公告组件)。
作为说明,它应该如下所示;
-零件-
-零件-
...继续...
..
您可以尝试 SectionList 并相应地传递数据。
<SectionList
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
我希望否则会起作用您可以在平面列表中根据某些条件呈现数据。
renderItem={(item, index)=>{{index/5 ==0 ? return Your view : retrurn your second view.}}
最终输出:
您可以这样做:
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [primary, setPrimary] = useState(data1);
const [secondary, setSecondary] = useState(data2);
const [final, setFinal] = useState();
/*
we are using this driver function to create the new array,
that we will use for as final list for rendering it on FlatList
*/
const driverFunction = () => {
let solution = [];
let j = 0;
for (let i = 0; i < data1.length; i++) {
if ((solution.length + 1) % 5 == 0) {
solution.push(data2[j]);
solution.push(data1[i]);
j++;
} else {
solution.push(data1[i]);
}
}
setFinal(solution);
};
useEffect(() => {
driverFunction();
}, []);
return (
<View style={styles.container}>
<FlatList
keyExtractor={(item) => item}
data={final}
renderItem={({ item, index }) => (
<Card
style={{
marginBottom: 5,
padding: 10,
backgroundColor: (index + 1) % 5 === 0 ? 'teal' : 'white',
}}>
<Text>{item}</Text>
</Card>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
// this is the primary data that we will use.
const data1 = [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20',
'21',
'22',
'23',
'24',
'25',
'26',
'27',
'28',
'29',
'30',
'31',
'32',
'33',
'34',
];
// this array is used for inserting it after certain interval, in this case 5.
const data2 = [
'Listone',
'Listtwo',
'Listthree',
'Listfour',
'ListFive',
'ListSix',
];
你可以在这里找到工作演示:Expo Snack
FlatList 中没有内置这样的功能。但是,这样做的一种方法是将广告添加到传递到 FlatList 的数据中,并修改renderItem
函数以使其也能够呈现它们。
({item}) => {
if (item.isAdd) {
// renderAdd
} else {
// renderContent
}
}