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相匹配。我可以判断它是800px,只有故意滚动经过FlatList认为结束的地方,才能访问最后的100px。FlatList的"额外"高度是,正好是。实际工作代码和零食链接(如果你安装了expo,可以在浏览器或手机上复制):

https://snack.expo.io/@sgardn04/平面列表标题示例

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()
)
}
}

我对柔性布局的工作原理有什么误解?我的印象是,FlatList组件被具有flexGrow: 1的东西有效地包裹,因此容器会增长以填充可用空间,但不会溢出。显然,列表中的垂直内容可能是空间允许的十倍,但它正好偏离了标题的高度,这一事实非常可疑。这里到底发生了什么?如果你想看看我认为的"工作"行为,试着在我发布的代码的呈现方法中切换注释的方法(如果你有一个更大的屏幕,所以它会溢出,那么就向数据中添加项目)。

只需将flex:1赋予父级View的样式即可。

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

FlatList实际上接受了一个用于设置标题样式的道具,这将比尝试创建自己的标题更好:FlatList标题

就flex而言,应该将flexflexGrow道具传递给实际包装FlatList的<View>组件。

我希望这能有所帮助!

最新更新