当使用标题渲染时,React Native FlatList 会延伸到屏幕之外

gar*_*rds 3 react-native expo react-native-flatlist

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

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

  <FlatList ... />
</View>
Run Code Online (Sandbox Code Playgroud)

但是,当我渲染标题时,FlatList组件的高度实际上是 800px,与包装组件的高度匹配flexGrow: 1。我可以看出它是 800px - 其中最后 100px 只能通过故意滚动到 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()
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 10

只需遵循flex:1父母的风格即可View

<View style={{flex:1}}>
<View></View>
<Flatlist/>
</View>
Run Code Online (Sandbox Code Playgroud)