首页 > 解决方案 > 使用标题呈现时,React Native FlatList 超出屏幕范围

问题描述

我正在尝试创建一个在FlatList组件上方呈现的标题。如果屏幕是 800px 高,标题是 100px 高,FlatList应该填满 700px(用flexGrow: 1),并且可以滚动(如果有太多ListItems)。基本标记如下:

<View style={{flexGrow: 1, backgroundColor: 'soothing-yellow-thunder'}}>
  <Header style={{height: 100}} />

  <FlatList ... />
</View>

但是,当我渲染标题时,FlatList组件的高度实际上是 800px,与包装组件的高度匹配flexGrow: 1。我可以说它是 800 像素——最后 100 像素只能通过有意滚动过去 FlatList 认为结束的位置来访问。“FlatList额外”高度与标题高度一样远。实际工作代码,以及小吃的链接(应该允许您在浏览器中重现,如果您安装了 expo,则可以在手机上重现):

https://snack.expo.io/@sgardn04/flatlist-header-example

import * as React from 'react';
import { Text, View, FlatList } from 'react-native';

export default class App extends React.Component {
  _renderList() {
    return (
      <FlatList
        data={[{key: '0', content: 'hello there 0'}, {key: '1', content: 'hello there 1'}, {key: '2', content: 'hello there 2'}, {key: '3', content: 'hello there 3'}, {key: '4', content: 'hello there 4'},]}
        renderItem={({item}) => { return <View style={{height: 140, borderColor: 'red', borderWidth: 1}}><Text>{item.content}</Text></View> }} />
    )
  }

  _renderListWithHeader() {
    return (
      <View style={{flexGrow: 1}}>
        <View style={{height: 70, backgroundColor: 'lime', alignItems: 'center', justifyContent: 'center'}}><Text>Header</Text></View>

        {this._renderList()}
      </View>
    )
  }

  render() {
    return (
      this._renderListWithHeader()
      // this._renderList()
    )
  }
}

我对 flex 布局的工作原理有什么误解?我的印象是FlatList组件被具有 的东西有效地包裹flexGrow: 1,因此容器将增长以填充可用空间但不会溢出。显然,列表的垂直内容可能是空间允许的十倍,但它完全偏离标题高度这一事实非常可疑。这里到底发生了什么?如果您想查看我认为“有效”的行为,请尝试在我发布的代码的渲染方法中切换注释方法(如果您的屏幕较大,则将项目添加到数据中以使其溢出)。

标签: react-nativeexporeact-native-flatlist

解决方案


简单地给flex:1你父母的风格View

<View style={{flex:1}}>
<View></View>
<Flatlist/>
</View>

推荐阅读