gpt4 book ai didi

react-native - React-Native FlatList 中的 getItemLayout

转载 作者:行者123 更新时间:2023-12-03 23:11:52 24 4
gpt4 key购买 nike

我正在尝试使用 react-native flatlist 的 scrollToIndex 函数。
我期望的是字母 ListView 。
太使用scrollToIndex,我需要设置flatlist组件的getItemLayout prop。
我已经用与父平面列表中的项目相同的字母表呈现了项目,并在子平面列表中渲染了项目,因此父平面列表的项目高度是不同的。
问题是,如果我给 getItemLayout Prop ,它会给我如下错误。

Invariant Violation: Invariant Violation: Invariant Violation: Invariant Violation: 当提供测量度量函数时,不应估计帧

<FlatList data={this.cityList}
renderItem={this.renderCityGroup}
style={styles.cityList}
keyExtractor={(item, index) => item + index}
getItemLayout={(data, index) => {
return {
length: data.height,
offset: data.total
}
}}
ref={ref => this.cityListRef = ref}
/>

这是我目前的代码。

最佳答案

在你的情况下,这很简单。内部data是你的元素。因此,如果您没有故意修改该数组,使其具有属性 heighttotal ,这根本行不通。

除此之外,offset不是所有元素的总高度,而是所有元素的高度相加之前的 发布的元素。

例子:

响应 native 请求它需要索引 3 处的项目,我们的项目的高度为 10 , 20 , 3040
对于第三个元素 offset您需要添加“第零个”、第一个和第二个,以便获得“起始 y 坐标”(或 x 取决于列表方向)。对于 length只需传递元素的高度,在我们的例子中是 40。

你最终返回的对象应该是这样的。

return {
index: index,
/*
You need to implement the two functions below so they actually return
what I described above.
*/
length: getItemHeight(index),
offset: getItemOffset(index),
}

如果有人在实现方面需要帮助,请发表评论,我可以给你一个提示:)。

但是还有一些陷阱。 React 团队要么犯了错误,要么认为有时在索引 -1 处请求元素很有趣(或者我不知道它实际上可能有用)。至少我没有。对于这种特殊情况,我在上面发布的代码之前添加了此代码:
// New, negative index preventing code
if (index === -1) return { index, length: 0, offset: 0 };
// Old code
return {
index: index,
length: getItemHeight(index),
offset: getItemOffset(index),
}

注意:如果您的项目都具有相同的高度,则整个计算结果为 方式更轻松。我只是:
return {
index,
length: itemHeight, // itemHeight is a placeholder for your amount
offset: index * itemHeight,
};

关于react-native - React-Native FlatList 中的 getItemLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com