首页 > 解决方案 > FlatList 使用 2 列。我有奇数个项目要显示。如何让最后一个项目左对齐?

问题描述

所以我有一个 FlatList 组件,它呈现奇数个项目。FlatList 有 2 列,我正在使用'space-around'列包装器。当项目数是偶数时,这很好用,但当它是奇数时,此列表中的最后一项将居中对齐。

因此,如果最后一行有一个项目,我如何让该项目左对齐(flex-start)?

          <FlatList
            columnWrapperStyle={ styles.columnWrapper }
            data={ inStockItems }
            keyExtractor={ item => item.itemId }
            horizontal={ false }
            numColumns={ 2 }
            renderItem={ ({ item }) => (
              <ItemContainer
                // style={ styles.userStoreItem }
                item={ item }
                navigate={ this.props.navigation }
                { ...this.props }
                admin
              />
            ) }
          />

styles.columnWrapper: {
    justifyContent: 'space-around',
  },

标签: cssreact-native

解决方案


您可以添加flex: 0.5到项目容器:

 <FlatList
      columnWrapperStyle={{justifyContent:'space-between', }}
      data={[{key: 'a'}, {key: 'b'}, {key: 'c'}]}
      keyExtractor={item => item.itemId}
      horizontal={false}
      numColumns={2}
      renderItem={({ item, index }) => (
        <View style={{backgroundColor:'red', flex: 0.5, margin: 4}}>{/*Here*/}
          <Text>{index}</Text>
        </View>
      )}
    />

推荐阅读