我在屏幕中有一个静态组件,有很多for循环渲染的组件。
下面的所有代码。
import React from "react";
import { View, Text, FlatList } from "react-native";
...
class FlatListScrollWithStatic extends React.Component {
render() {
return (
<View style={{ flex: 1 }}>
<FriendsTop /> // the static component
<FlatList
style={{ flex: 1 }}
data={this.props.friendsCard}
renderItem={({ item }) => <FriendsCard {...item} />} // the for loop rendered components
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
现在,我想将FriendsTop迁移到Flatlist,让它与渲染的组件一起滚动,我该如何更改代码?
答案 0 :(得分:4)
Flatlist具有一个接受JSX元素的道具ListHeaderComponent
。
所以:
import React from "react";
import { View, Text, FlatList } from "react-native";
...
class FlatListScrollWithStatic extends React.Component {
render() {
return (
<View style={{ flex: 1 }}>
<FlatList
style={{ flex: 1 }}
data={this.props.friendsCard}
renderItem={({ item }) => <FriendsCard {...item} />} // the for loop rendered components
keyExtractor={(item, index) => index.toString()}
ListHeaderComponent={<FriendsTop />}
/>
</View>
);
}
}
答案 1 :(得分:2)
这可能对您有用:
import React, { Fragment } from "react";
...
<FlatList
style={{ flex: 1 }}
data={this.props.friendsCard}
renderItem={({ item }, index) => (
<Fragment>
{ !index && <FriendsTop /> } // Render when !index is truthy (i.e. index === 0)
<FriendsCard {...item} />
</Fragment>
)}
keyExtractor={(item, index) => index.toString()}
/>
答案 2 :(得分:0)
我有两种方法可以执行此操作,第一种方法是使用扁平表的标头组件
但是我想如果您想将静态数据与从获取数据中获取的数据结合起来
<FlatList
inverted
data={this.state.data.concat({
"id":1,
"user_id": 1,
"title": "all",
"similar_title": null,
"description": null,
"font_icon": null,
"default_distance": 8,
"visible": "yes",
"priority": "no",
"image": null,
"created_at": null,
"updated_at": "2018-06-14 22:13:58"
})}
numColumns={4}
renderItem={({item}) =>