【发布时间】:2021-04-30 18:25:43
【问题描述】:
我有一个平面列表。数据数组是一本书的内容(段落、图像、子标题)。如何在我的 FlatList 上正确实现 getItemLayout 属性?我知道这是为了告诉 FlatList 每个项目的高度以使其更具性能。但是我如何找出每个项目的大小?这是我通过猜测来任意确定含义的东西吗?每件商品的尺寸都不同。我尝试在 getItemLayout 中输入随机值只是为了看看会发生什么,但是我真的不知道如何判断哪个值是正确的值。
这是我的平面列表
<FlatList
ref={flatListRef}
contentContainerStyle={{ paddingHorizontal: 10 }}
showsVerticalScrollIndicator={true}
initialNumToRender={10}
data={dataRef}
renderItem={renderItem}
onScrollToIndexFailed={scrollFailToIndex}
getItemLayout={(data, index) => {
return { length: 0, offset: 0 * index, index };
}}
/>
这是我的数据数组的一部分...
const dataRef = [
{
img: "tr1Cover",
id: "1Tr 1.cover",
key: "0",
},
{
text: "Copyright 1933,1940,1941\nAll rights reserved\nV. T. HOUTEFF.",
style: "plainCenterText",
key: "1",
},
{
text:
"In the interest of reaching every truth-seeking mind that desires to escape the path that leads to destruction of both body and soul, this tract will be distributed free of charge as long as this issue lasts.",
id: "1Tr 2.1",
style: "plainText",
key: "2",
},
{
text: "PREFACE PERSONALLY WATCHING FOR EVERY RAY OF LIGHT.",
style: "subHeading",
key: "3",
},
{
text:
"One who entrusts to another the investigation of a message from the Lord, is making flesh his arm, and thus is foolishly acting as without a mind of his own. And ”the mind that depends upon the judgment of others is certain, sooner or later, to be misled. ” -- Education, p. 231.",
id: "1Tr 3.1",
style: "plainText",
key: "4",
},
这是我的 renderItem 函数...
const renderItem = useCallback(({ item }) => <ListItem item={item}></ListItem>, []);
这是我的 ListItem 组件...
class ListItem extends PureComponent {
constructor(props) {
super(props);
}
render() {
if (this.props.item.img) {
return (
<Image
source={Images[this.props.item.img]}
resizeMode="stretch"
style={{
alignSelf: "center",
}}
/>
);
}
if (this.props.item.text) {
return (
<Text selectable={true} style={styles[this.props.item.style]}>
{this.props.item.text}
<Text style={styles.pagination}>{this.props.item.id}</Text>
</Text>
);
}
}
}
我有时会收到此警告...
VirtualizedList:您有一个更新缓慢的大型列表 - 确保您的 renderItem 函数呈现遵循 React 性能最佳实践的组件,例如 PureComponent、shouldComponentUpdate 等。 Object { “内容长度”:14102.4765625, “dt”:630, "prevDt": 2141,
有人告诉我这是因为我没有使用 getItemLayout 道具。我还注意到滚动有时有点小故障/滞后。我的目标是在没有类组件的情况下完成我的项目,但是我听说使用 PureComponents 是对高性能 flatLists 的推荐,所以我认为它可以解决我的滞后问题。
为了清楚起见,仅显示内容的样子...
【问题讨论】:
标签: javascript react-native react-native-flatlist