【问题标题】:React Native: ZIndex with dynamic viewsReact Native:具有动态视图的 ZIndex
【发布时间】:2025-12-17 12:40:01
【问题描述】:

我是 React Native 的新手,我正在尝试构建一个应用程序,在该应用程序中我向我的用户呈现一个平铺的概述。我使用具有 3 列的 FlatList 构建了这个平铺概览。我需要让它看起来像所有物品都挂在一根绳子上,该绳子在我拥有的瓷砖后面垂直延伸,我试图通过将我的“项目”视图的 Z-Index 设置为 1000 和我的 zIndex “绳索”视图为 1。请参见下面的示例:

我的单元格的代码如下所示:

export default class ItemButton extends Component {

  //

render() {
    const { item, style, onPress } = this.props
    console.log('style for itemButton: ', style)
    return (
        <TouchableOpacity style={style} onPress={onPress}>
            <Image style={{zIndex:1000, width: style.width, height: style.height}} resizeMode={'contain'} source={require('../Artwork/Items/cta-enter.png')}></Image>
            <Image style={{top: -Math.abs(style.height + 100), height: 200, width: 30, zIndex:1, alignSelf: 'center'}} source={require('../Artwork/Items/rope.png')} resizeMode={'contain'}></Image>
        </TouchableOpacity>        
    );
  }
}

我在我的 FlatList 中实现它如下:

renderCollectionItem(item) {
    return <ItemButton item={item} style={styles.buttonStyle} onPress={() => this.collectionItemPressed(item)} />
  }

render() {
return (
   <FlatList
  style={{width: collectionViewWidth, flexDirection: 'row', overflow: 'visible', top: this.props.style.top}}
  contentContainerStyle={[{left: this.props.horizontalSpacing / 2}, internalStyles.collectionViewContentStyle]}
  data = { this.convertToIndexed(this.props.items) }
  renderItem = {({item}) => (
    this.renderCollectionItem(item[0])
  )}
  numColumns={(3)}
  key={(Helpers.isPortrait() ? this.state.portraitRowSize : this.state.landscapeRowSize)}
  keyExtractor={(item, index) => index.toString()}
/>
);
}

但是,这不起作用,因为 React-Native 总是将稍后渲染的视图放置在更高的 Z-Index 上。

问题: 我应该如何配置我的 FlatList 以获得我需要的结果,如上图所示?

【问题讨论】:

  • 可以显示一些代码,以便我们仔细看看你的实现吗?
  • @HaiderAli 我刚刚用单元格中的代码更新了我的问题,这是我添加绳索的地方
  • 我已经检查了你的实现,它看起来很好snack.expo.io/@hiaiderali101/honest-almond,我认为你需要检查你是如何在 FlatList 上实现它的。 ps 给 zIndex: 1 和 -1 也适用于你的情况
  • 嗨!感谢您的努力。您的代码示例有效,因为呈现顺序。在我的平面列表中,我逐个渲染所有元素,这会自动为它们提供更高的 Z-Index。这是我试图通过这个问题得到答案的问题,而不仅仅是常规的 Z-Index 配置
  • 你能不能也展示你的 FlatList 实现?

标签: css react-native z-index styling


【解决方案1】:

不幸的是 react-native 不支持 z-index .. 我在使用动态组件时遇到了同样的问题, 解决方案是在两个元素的样式中使用 Elevation 属性,这是诀窍:

  • 将您希望位于较高海拔的元素指定为 15。
  • 给另一个元素你想成为另一个元素的底部 海拔 说 5 。 结果将正是你想要的..

【讨论】: