React-Native FlatList 中的 getItemLayout

getItemLayout in React-Native FlatList

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

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不是所有元素的总高度,而是所有元素的总高度,它在发出的元素之前。

示例:

React native 请求它需要索引 3 处的项目,我们的项目的高度为 10203040

对于第三个元素 offset,您需要添加 "zeroth"、第一个和第二个元素,以便获得 "starting y coordinate"(或 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,
};