首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >具有列的React原生FlatList,最后一个项目宽度

具有列的React原生FlatList,最后一个项目宽度
EN

Stack Overflow用户
提问于 2017-04-20 01:59:10
回答 8查看 89.9K关注 0票数 89

我使用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}/> }
/>

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

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', height: 130}} ></View>

它工作得很好,但如果项目的数量是奇数,最后一行只包含一个项目,该项目将延伸到整个屏幕的宽度。

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

EN

回答 8

Stack Overflow用户

发布于 2017-07-13 23:22:57

您可以尝试通过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>
票数 19
EN

Stack Overflow用户

发布于 2019-05-06 13:16:48

这是设置带有列且间隔均匀的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"
        }
    });
票数 17
EN

Stack Overflow用户

发布于 2019-01-17 13:22:56

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

<View style={{ flex: 1, margin: 5, backgroundColor: '#ddd', height: 130, maxWidth: '50%'}} ></View>
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43502954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档