React Native FlatList with columns,Last item width

Esc*_*ar5 57 react-native react-native-flatlist

我正在使用FlatList来显示两列中的项目列表

<FlatList style={{margin:5}}
  data={this.state.items}
  numColumns={2}
  keyExtractor={(item, index) => item.id }
  renderItem={(item) => <Card image={item.item.gallery_image_url} text={item.item.name}/> }
/>
Run Code Online (Sandbox Code Playgroud)

卡组件只是一个具有一些样式的视图:

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', height: 130}} ></View>
Run Code Online (Sandbox Code Playgroud)

它工作正常,但如果项目数是奇数,则最后一行只包含一个项目,该项目会延伸到屏幕的整个宽度.

如何将项目设置为与其他项目相同的宽度?

在此输入图像描述

小智 26

您的情况下使用flex:1/2

因此:你的项目应该有弹性的1 /(列数),如果你有3列的项目应具有弹性:1/3

  • 当我给出flex:1/2时,最后一个项目的宽度大于以前的项目,请问如何解决这个问题 (4认同)
  • 不知道为什么没有将此标记为答案。这是最简单正确的解决方案! (2认同)
  • 最后一行稍宽的问题可能与边距有关;尝试将项目包装在没有边距的视图中。 (2认同)

Rya*_*ull 24

你可以在这里尝试一些事情.

A)为卡设置预定义的宽度(可能等于您设置的高度?).然后你可以使用alignItems,以使卡位于中间或左侧 - 不确定你想在这里.

B)如果有偶数卡片,您可以在末尾添加一个空视图以填充此空间.我发现这种方法非常笨重,但在尝试为未来元素留出空间时非常有用.

C)简单地使用alignItems: 'space-between,我喜欢使用它来居中项目,但你必须定义宽度,或使用类似的东西flex:0.5

我建议更多地研究一下flexbox来帮助你解决这个问题,因为很难说出这种情况的背景.我假设上述方法会有所帮助,但如果没有,这里有一些链接供您查看 -

第一个链接

第二个环节

第三个环节 链接破碎

希望这可以帮助.如果您需要进一步澄清 - 请问

  • B 是一个合理的 hack。选项A是多余的,只需添加flexWrap即可设置为对齐方式。在这种情况下 numColumns 的目的是什么? (2认同)

sky*_*lor 17

您可以尝试通过Dimensions获取设备的当前宽度,根据要渲染的列数进行一些数学运算,减去边距并将其设置为minWidth和maxWidth.

例如:

const {height, width} = Dimensions.get('window');
const itemWidth = (width - 15) / 2;

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', minWidth: {this.itemWidth}, maxWidth: {this.itemWidth}, height: 130}} ></View>
Run Code Online (Sandbox Code Playgroud)


jas*_*ard 12

这是FlatList使用列设置样式并均匀间隔的最简洁的方法:

    <FlatList style={{margin:5}}
        numColumns={2}                  // set number of columns 
        columnWrapperStyle={style.row}  // space them out evenly
        
        data={this.state.items}
        keyExtractor={(item, index) => item.id }
        renderItem={(item) => <Card image={item.item.gallery_image_url} text={item.item.name}/> }
    />       

    const style = StyleSheet.create({
        row: {
            flex: 1,
            justifyContent: "space-around"
        }
    });
Run Code Online (Sandbox Code Playgroud)


小智 6

原因是你的卡片有风格flex: 1,所以它会尝试扩大所有剩余的空间。您可以通过添加maxWidth: '50%'到您的卡片样式来修复它

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', height: 130, maxWidth: '50%'}} ></View>
Run Code Online (Sandbox Code Playgroud)


Ami*_*mit 5

@Emilius Mfuruki 的建议很好,但如果您有不同长度的文本,它就不能完美地工作。然后在您的项目视图中使用此宽度:

const {height, width} = Dimensions.get('window');
const itemWidth = (width - (MarginFromTheSide * 2 + MarginInBetween * (n-1))) / n;
Run Code Online (Sandbox Code Playgroud)

在 FlatList 中使用:

columnWrapperStyle={{
            flex: 1,
            justifyContent: 'space-evenly',
          }}
Run Code Online (Sandbox Code Playgroud)

完美运行。