【问题标题】:React native Flatlist items with negative margin反应具有负边距的原生 Flatlist 项目
【发布时间】:2020-03-10 12:06:37
【问题描述】:

我在 Android 上有一个简单的垂直 Flatlist,我想用负边距渲染它的一些项目。目标是让这些项目看起来比平面列表更宽。

类似这样的东西,红色是平面列表中的一个项目:

不幸的是,项目的边缘被 Flatlist 的边缘切割。

有没有办法显示比呈现它们的平面列表更宽的项目?

编辑: 我知道我可以通过为列表中除红色项目之外的每个项目添加边距/填充来实现插图的视觉效果。我想知道的是是否可以使特定项目比 Flatlist 本身更宽(不仅仅是比其他项目更宽)

我宁愿对需要更宽的一个项目进行风格化,而不是其他所有项目。

【问题讨论】:

  • 你能提供一些图片,我们可以看到它应该是什么样子吗?
  • @Tim 我添加了一些插图

标签: react-native react-native-flatlist


【解决方案1】:

我自己实际上从来没有在 FlatList 中制作一个比整个 flatList 更大规模的项目,因为我知道这是一个坏主意,而且看起来很丑,想象一下一个带有重叠 verticalScrollIndicator 的项目。但更好的方法是你可以像这样添加一个视图。

...FlatList tag.....
renderItem={({ item, index }) => {
  return (
    <View style={{ paddingHorizontal:item.isWider ? 0 : '5%' }}>
        ....Children
    </View>
  )
}}

您还可以编写仅适用于某些特定项目索引的语句。 顺便说一句,滚动指示器不会与任何项目重叠,它有一个可控的、更好看的 UI。

【讨论】:

  • 我编辑了我的问题。我想让单个红色项目比平面列表更宽,而不是对所有其他项目进行样式化。
【解决方案2】:

当您想要渲染特定项目时没有边距值,您唯一需要做的就是覆盖样式。

我根据您的要求创建一个示例应用程序。

import React, { Component } from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text } from 'react-native';

const DATA = [
    {
        id: 1,
        title: 'First Item',
    },
    {
        id: 2,
        title: 'Second Item',
    },
    {
        id: 3,
        title: 'Third Item',
    },
    {
        id: 4,
        title: 'Forth Item',
    },
    {
        id: 5,
        title: 'Fifth Item',
    },
    {
        id: 6,
        title: 'Sixth Item',
    },
];

export default class App extends Component {

    renderItems = ({ item }) => (
        // Suppose if you want to change margin value & background color of id == 3
        <View style={item.id !== 3 ? styles.item : [styles.item, { backgroundColor: 'red', margin: 0 }]}>
            <Text>{item.title}</Text>
        </View>
    )

    render() {
        return (
            <SafeAreaView style={styles.container}>
                <FlatList
                    data={DATA}
                    renderItem={this.renderItems}
                    keyExtractor={item => item.id}
                />
            </SafeAreaView>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: 20,
    },
    item: {
        backgroundColor: 'green',
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
    },
});

希望这对您有所帮助。如有疑问,请随意。

【讨论】:

  • 我编辑了我的问题。我想让单个红色项目比平面列表更宽,而不是对所有其他项目进行样式化。
【解决方案3】:

根据您提供的图片,并且只设置特定列表项的样式,我可以更改align-selfwidth 和否定margin 以实现您想要的。

应用特定项目

<FlatList
  contentContainerStyle={styles.list}
  data={data}
  renderItem={({ item, index }) => (
    <View style={[styles.item, index === 3 && styles.oversize]} />
  )}
/>

风格:

oversize: {
  backgroundColor: 'orange',
  alignSelf: 'stretch',
  width: 'auto',
  marginHorizontal: -16,
},

Here is working example

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 2018-04-26
    • 2022-01-02
    • 2018-12-02
    • 2018-04-17
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多