reactjs - 当其中一些必须是全宽时,如何在具有 2 列的反应原生 FlatList 中呈现项目
问题描述
我想在 React Native 中默认呈现 2 列的产品列表,但如果任何项目是特殊产品,则将其设为全宽。
const data = [
{id: '1', name: 'Item1', price: 25, special_product: false},
{id: '2', name: 'Item2', price: 15, special_product: false},
{id: '3', name: 'Item3', price: 11, special_product: true},
{id: '4', name: 'Item4', price: 22, special_product: false},
{id: '5', name: 'Item5', price: 32, special_product: false},
{id: '6', name: 'Item6', price: 22, special_product: false},
{id: '7', name: 'Item7', price: 22, special_product: false},
]
我想得到这样的 FlatList 结构:
[Item 1][Item2]
[Special Item3]
[Item4] [Item5]
[Item6] [Item7]
我的代码现在非常简单:
<FlatList
ref={(ref) => { this.flatListRef = ref; }}
contentContainerStyle={{ flexGrow: 1 }}
horizontal={false}
data={data}
keyExtractor={({ id }) => id}
onRefresh={this.onListRefresh}
refreshing={refreshing}
renderItem={this.renderItems}
ListHeaderComponent={this.renderHeader}
ListEmptyComponent={this.renderEmptyList.bind(this, data, use)}
/>
我的项目容器样式如下所示:
const Styles = StyleSheet.create({
container: {
flex: 0.5,
margin: Layout.Margin.Narrow,
shadowColor: ShadowColor.Standard,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.5,
shadowRadius: 4,
elevation: 5,
borderBottomLeftRadius: 5,
borderBottomRightRadius: 5,
},
...
});
renderItem
由函数呈现的项目:
// Item
...
return (
<TouchableWithoutFeedback
onPress={() => console.log('user clicked on the item')}>
<View style={{
...itemStyle.container
}}
<StyledText
type={"small"}
numberOfLines={1}
allowFontScaling={false}
style={itemStyle.centerText}>
{name}
</StyledText>
</View>
</TouchableWithoutFeedback>
我怎样才能做到这一点?我正在使用 React Native v0.60.5
解决方案
您可以使用列数道具并提供 100% 的宽度,这将提供您需要的输出。
这是一个工作示例,您可以根据需要将其应用到您的项目样式中。
平面列表代码
<FlatList
numColumns={2}
data={data}
renderItem={({ item }) => (
<Item
id={item.id}
title={item.name}
selected={item.special_product}
/>
)}
keyExtractor={(item) => item.id}
/>
渲染项功能
function Item({ id, title, selected }) {
return (
<TouchableOpacity
onPress={() => {}}
style={[
selected ? { width: '100%' } : { width: '50%' },
{ backgroundColor: selected ? '#6e3b6e' : '#f9c2ff' },
]}>
<Text style={{}}>{title}</Text>
</TouchableOpacity>
);
}
如您所见,我已根据所选标志有条件地设置宽度。
推荐阅读
- mulesoft - Mulesoft 中的全局变量
- android - 使用模拟器的 Visual Studio 看不到 android avd 管理器?
- firebase - Firebase 数据库未更新值
- blazor - Blazor MatTable 页面大小更改
- angular - 角度 2+ 有没有办法强制检测变化?
- oracle - 如何 /as sysdba 到 Docker 上运行的数据库?
- java - 如何在 Java 中为断开连接的客户端杀死服务器中的线程
- php - 如何提交从 URL 检索表单并使用 PHP 提交?
- javascript - OnEdit - 不删除所有数据
- django - 如何修改路由器和视图集以进行模板渲染