【问题标题】:snapToAlignment center not working in first rendersnapToAlignment 中心在第一次渲染中不起作用
【发布时间】:2022-08-02 17:52:46
【问题描述】:

我正在研究类似 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}
  />

从第二个项目开始滚动后或当我们触摸它时,它工作正常,它正在调整到中心,但是当它第一次渲染时它不在中心。

用户卡组件看起来像这样on first render

Second Item After scrolling

第二项完全居中,我希望第一项居中。

我尝试使用带有这些功能的 useEffect 向上移动卡滚动到偏移,滚动到项目,滚动到索引等等,但他们需要在第一次渲染时不可用的平面列表参考。

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

    标签: react-native react-native-flatlist react-native-scrollview


    【解决方案1】:

    您将需要使用滚动到索引FlatList 的方法并使用滚动到所需的索引布局事件

    在里面滚动到索引打电话,通过视图位置的价值0.5这将使视图居中(在您的情况下捕捉)

    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'}
        ...
    />
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多