我正在 React Native 中创建一个应用程序,我将在其中多次使用
<FlatList>
组件。
现在,所有列表都非常相似,唯一的动态元素是列表内的数据。唯一的问题是数据是一个对象,并且对于每个列表,该对象都是不同的。我无法弄清楚如何创建一个生成列表的通用函数,并且还能够从数据对象中呈现特定属性。
下面的代码显示了大多数列表的代码,您可以看到应添加动态数据的注释
function CreateList(props) {
return (
<FlatList data={props.data}
style={{marginBottom: 165}}
renderItem={({item, index}) => {
return (
<TouchableOpacity style={{ paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: "lightgray" }} onPress={() => {
props.navigation.navigate(props.navigateTo, props.dataToPass)
}}>
<View style={styles.tile}>
{/* {React.cloneElement(props.children, item)} */}
<View>
{/* Add dynamic data in a component */}
</View>
<MaterialIcons style={{marginRight: 14}} name="keyboard-arrow-right" size={24} color="lightgray" />
</View>
</TouchableOpacity>
);
}}
/>
);
}
为所有列表创建单独的组件是一个不错的选择吗?
您可以创建一个用于在 renderItem 中渲染自定义内容的道具,然后使用展开运算符来允许进一步自定义其他平面列表道具(demo)
export default function GenericList({
data,
navigation,
navigateTo,
dataToPass,
renderItemContent,
// allows customizing list props
...flatListProps
}) {
return (
<FlatList
{...flatListProps}
data={data}
style={[{ marginBottom: 165 },flatListProps.style]}
renderItem={({ item, index }) => {
return (
<TouchableOpacity
style={{
paddingVertical: 10,
borderBottomWidth: 1,
borderBottomColor: 'lightgray',
}}
onPress={() => {
navigation.navigate(navigateTo, dataToPass);
}}>
<View style={styles.tile}>
<View>
{renderItemContent({item,index})}
</View>
<MaterialIcons
style={{ marginRight: 14 }}
name="keyboard-arrow-right"
size={24}
color="lightgray"
/>
</View>
</TouchableOpacity>
);
}}
/>
);
}
然后使用:
<View style={styles.listContainer}>
<Text style={styles.listTitle}>List A</Text>
<GenericList
data={data1}
renderItemContent={(props) => <RenderItemContent1 {...props} />}
navigation={navigation}
navigateTo="Settings"
dataToPass={someData1}
/>
</View>
<View style={styles.listContainer}>
<Text style={styles.listTitle}>List B</Text>
<GenericList
data={data2}
renderItemContent={(props) => <RenderItemContent2 {...props} />}
navigation={navigation}
navigateTo="Settings"
dataToPass={someData2}
/>
</View>