首页 > 解决方案 > 如何为 ReactNative SectionList 项目可见性添加偏移量

问题描述

我有一个带有 SectionList 的 ReactNative 应用程序。列表上有一个绝对定位的标题,其中包含部分的名称。滚动此列表时,我需要更新当前滚动的部分。

这是我的代码:

const handleChangeSelectedIndexWithScroll = ({ viewableItems }) => {
  if (!viewableItems || viewableItems.length === 0) {
    return;
  }

  // Get which section is visible on the screen
  const visibleSectionsId = viewableItems.map(
    (viewableItem) => viewableItem.section.index
  );

  // Say that the currently scrolled section is the first one that has any visible item.
  // By doing this, if the first section has any single visible item, it will be the one selected
  setCurrentSectionScrolled(Math.min(...visibleSectionsId));
};

<SectionList
        ref={recipeDetailsRef}
        sections={data}
        onViewableItemsChanged={handleChangeSelectedIndexWithScroll}
/>

问题: 使用绝对标题,滚动没有很好地反映,因为 RN 认为该部分的项目在屏幕上可见,而实际上它们可以隐藏在标题后面。

截图 在此处输入图像描述 在这张图片上,你可以看到当前选择的部分是“Ingredients”,而事实上,我们已经在“Materiels”上,因为在绝对标题后面,还有一个对 RN 可见的成分

考虑的解决方案:

这就是为什么我想知道是否有一个单一的解决方案可以对 RN 说:“请考虑这个列表有 50px 的偏移量”,这样如果它们在这个偏移量中,他们就不会考虑可见项目

谢谢

标签: react-nativereact-native-flatlistreact-native-sectionlist

解决方案


如果要更改活动项,可以使用以下方法。

const handleChangeSelectedIndexWithScroll = ({ changed , viewableItems }) => {
  if (!viewableItems || viewableItems.length === 0) {
    return;
  }
  
  const sectionIndex = viewableItems.length - changed.length

  setCurrentSectionScrolled(sectionIndex);
};

推荐阅读