【问题标题】:React Native - Horizontal Flatlist with column wrapper doesn't take flex properly as required?React Native - 带有列包装器的水平平面列表没有按要求正确使用 flex?
【发布时间】:2020-04-11 04:40:39
【问题描述】:

我有一个动态平面列表,其中的值应该在 3 列的水平列表中呈现。但是,我无法让它按我的意愿显示。

我正在尝试以下代码,

    let data = ["item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8"];
    const { width } = Dimensions.get('window');
    const itemWidth = (width - 12) / 3;

           <FlatList
                    columnWrapperStyle={{ justifyContent: 'space-around', alignItems: 'flex-start' }}
                    numColumns={3}
                    data={data}
                    showsVerticalScrollIndicator={false}
                    showsHorizontalScrollIndicator
                    keyExtractor={(item, index) => `${index}${item}`}
                    renderItem={(item) => {
                        return (
                            <View style={{ flex: 1, backgroundColor: '#ddd', minWidth: itemWidth, maxWidth: itemWidth }}>
                                <Text >
                                    Hello World
                            </Text>
                            </View>
                        );
                    }}
                />

但是,输出不是我想要的。

假设列表的长度是 3 的倍数,例如 6、9、12,它可以按我的意愿工作。

但是,如果列表长度为 8,则前两行可以正常呈现。但是,第三行为其余两项提供了全部空间。我不想要。

目前我的输出如下

但输出应该是

任何人都可以提出解决方法吗?

谢谢。

【问题讨论】:

    标签: react-native react-native-android react-native-ios react-native-flatlist react-native-scrollview


    【解决方案1】:

    请参阅我可以为您提供一种合乎逻辑的解决方案,并且我假设您想在 Flatlist 中绘制文本。对于这种情况,您需要为相应的空插槽附加一个空 div。

    如果您希望 numOfColumns 为 3,

    let data = ["item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8"];
    

    先检查余数和要添加的行数

    let numOfRowsToBeAdded = 3-(data.length%3);
    // here im ommitting if we get 0 as remainder as its not required
    if(numOfRowsToBeAdded){
    for(let i=0;i<numOfRowsToBeAdded;i++){
    data.push(null);
    }
    }
    

    希望你明白逻辑。随时怀疑。帮不上忙

    【讨论】:

      【解决方案2】:

      由于您手动计算itemWidth,您可以使用justify: flex-end 作为您的columnWrapperStyle,然后将marginRight: 6 添加到每行中的每个第一项和第二项:

      renderItem={(item, index) => {
        const isThirdColumn = (index + 1) % 3 === 0;
        const marginRight = isThirdColumn ? 0 : 6;
      
        return (
          <View style={{ marginRight, ...otherStyles }}>
      

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 1970-01-01
        • 2020-04-22
        相关资源
        最近更新 更多