首页 > 解决方案 > 当其中一些必须是全宽时,如何在具有 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

标签: reactjsreact-nativereact-native-flatlist

解决方案


您可以使用列数道具并提供 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>
  );
}

如您所见,我已根据所选标志有条件地设置宽度。


推荐阅读