SnaptoAlignment Center在第一次渲染中不起作用

发布于 2025-01-30 18:17:39 字数 927 浏览 4 评论 0原文

我正在研究Instagram Snap Scrolling之类的事情。用户卡应以中心为中心(每张卷轴上一张卡)。

  <FlatList
    data={items}
    renderItem={({item}) => <UserCardComponent name={item.name} />}
    keyExtractor={item => item.id}
    snapToAlignment="center"
    decelerationRate={'fast'}
    snapToInterval={Dimensions.get('window').height}
    showsVerticalScrollIndicator={false}
  />

从第二个项目滚动或触摸它后,这是正常工作的,它正在调整为中心,但是当它首次渲染时,它不在中心。

用户卡组件看起来像 在第一个渲染上

滚动后的第二个项目

第二个项目是完全中心的,我希望将第一个项目集中为中心。

我试图使用这些功能使用使用效率向上移动卡片 scrolltooffset scrolltoitem scrolltoIndex 等。但是它们需要flatlist参考,而这些flatList参考却不可用。第一次渲染。

提前致谢。任何帮助将不胜感激

I'm working on something like instagram snap scrolling. The User Card should be centered (One card on each scroll).

  <FlatList
    data={items}
    renderItem={({item}) => <UserCardComponent name={item.name} />}
    keyExtractor={item => item.id}
    snapToAlignment="center"
    decelerationRate={'fast'}
    snapToInterval={Dimensions.get('window').height}
    showsVerticalScrollIndicator={false}
  />

This is working fine after scrolling from the second item onwards or when we touch it, it is adjusting to center but when it is rendered first time its not in the center.

User Card Component looks like this
on first render

Second Item After scrolling

Second item is perfectly centered, I want first item to be centered.

I tried to move the card upwards using useEffect with these functions scrollToOffset,scrollToItem, scrollToIndex etc. but they needed flatlist reference which is not available while rendering first time.

Thanks in advance. Any help will be appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖上的星空 2025-02-06 18:17:39

使用 on Laylayout 滚动到所需的索引

您将需要使用 scrolltoIndex flatlist的方法,然后在 scrollToIndex call中 ,Pass view> viewposition < /strong> 0.5 的值,将视图(在您的情况下为snap)

https://reaectnative.dev/docs/flatlist#scrolltoindex

const ref = useRef<FlatList>(null);

const onLayout = () => {
    ref.current?.scrollToIndex({
        index: 10,
        viewPosition: 0.5,
    });
};

<FlatList
    ref={ref}
    onLayout={onLayout}
    snapToAlignment={'center'}
    ...
/>

You will need to use scrollToIndex method of FlatList and scroll to the desired index using onLayout event

In the scrollToIndex call, pass viewPosition value of 0.5 which will center the view (snap in your case)

https://reactnative.dev/docs/flatlist#scrolltoindex

const ref = useRef<FlatList>(null);

const onLayout = () => {
    ref.current?.scrollToIndex({
        index: 10,
        viewPosition: 0.5,
    });
};

<FlatList
    ref={ref}
    onLayout={onLayout}
    snapToAlignment={'center'}
    ...
/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文