代码之家  ›  专栏  ›  技术社区  ›  BautistaDiSanto

React原生香草旋转木马动画

  •  0
  • BautistaDiSanto  · 技术社区  · 1 年前

    我的旋转木马目前正在运行,但它的动画不稳定。 我处理一组图像,在开始和结束时我使用相同的图像。 当显示数组的最后一个元素时,它应该返回到第一个元素而不会被注意到变化,但会出现闪烁,有时它会中断并反向运行动画以显示数组的第一个元素(它从结束滚动到开始,而不是从开始滚动到结束)。

    import { View, SafeAreaView, Animated, Dimensions } from 'react-native';
    import { useRef, useEffect } from 'react';
    
    const arrayOfImages = [
      {key: 1, Component: SvgImage1 },
      {key: 2, Component: SvgImage2 },
      {key: 3, Component: SvgImage3 },
      {key: 4, Component: SvgImage4 },
      {key: 5, Component: SvgImage5 },
      {key: 6, Component: SvgImage1 },
    ]
    
    const { width } = Dimensions.get('screen');
    
    const MyCarousel = () => {
      const flatListRef = useRef(null);
      let index = 0;
    
      useEffect(() => {
        const interval = setInterval(() => {
          index = index === arrayOfImages.length - 1 ? 0 : index + 1;
          flatListRef.current.scrollToIndex({
            index,
            animated: true,
          });
          if (index === arrayOfImages.length - 1) {
            setTimeout(() => {
              index = 0;
              flatListRef.current.scrollToIndex({
                index,
                animated: false,
              });
            }, 3400);
          }
        }, 3500);
    
        return () => clearInterval(interval);
      }, []);
    
      return (
        <SafeAreaView className="w-full bg-white">
          <Animated.FlatList
            data={arrayOfImages}
            ref={flatListRef}
            horizontal
            showsHorizontalScrollIndicator={false}
            pagingEnabled
            keyExtractor={item => `${item.key}`}
            renderItem={({ item }) => (
              <View
                style={{
                  width,
                }}
              >
                <item.Component style={{ alignSelf: 'center', width }} />
              </View>
            )}
          />
        </SafeAreaView>
      );
    };
    
    export default MyCarousel;
    

    我认为这与setInterval和setTimeout函数处理的时间有关,但我无法使其顺利工作。

    0 回复  |  直到 1 年前