在 React native 中使用 scrollview 同步 carrousel 图像的问题

Problem in sync carrousel images with scrollview in React native

我在使用此实现在 React Native 中将文本和旋转木马图像与滚动视图同步时遇到很多问题。我尝试了很多选项来解决这个问题,比如 setTimeout 和 contentOffset。

问题是第一个渲染器没有调用 scrollTo,这会使显示的文本和图像不同步。

我在 React Native https://github.com/facebook/react-native/issues/6849 中发现了这个问题,但我无法从中提取解决方案。有人可以帮助我吗?

import * as React from "react";
import { View, Text,ScrollView, useWindowDimensions } from "react-native";

const data = [
  {
      color: 'red'
  },
  {
      color: 'blue'
  },
  {
      color: 'black'
  },
  {
      color: 'green'
  }
]

export default function App() {

  const scrollViewRef = React.useRef();
  const { width } = useWindowDimensions();
  const [index, setIndex] = React.useState(0);

  const offsetContent = (offset) => {
      scrollViewRef.current.scrollTo({ x: offset, animated: false });
  };

  const autoScroll = () => {
    const size = data.length - 1;
    setIndex(size === index ? 0 : index + 1);

    const offset = width * index;

    offsetContent(offset);

    console.log(`${size} ${index} ${offset}`);
  };


  React.useEffect(() => {
    const timer = setTimeout(autoScroll, 3000);

    return () => clearTimeout(timer);
  });

  return (
    <View
      style={{
        justifyContent: "center",
        alignItems: "center",
      }}
    >

      <ScrollView
        ref={scrollViewRef}
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={{ height: width / 1.5 }}
        pagingEnabled
        contentOffset={{ x: 380, y: 0 }}
      >
        {data.map((item) => (
          <View key={item.color} style={{width, height: 280, backgroundColor: item.color}} />
        ))}
      </ScrollView>


      <Text>{data[index].color}</Text>
    </View>
  );
}

看!!

const autoScroll = () => {
    const size = data.length - 1;
    setIndex(size === index ? 0 : index + 1);

    const offset = width * index;

    offsetContent(offset);
    // Here you calculate offset based on index..
    // When you increase index and update the state, you need another hook do detect when this index is updated and then calculate an offset.
}


// Add this hook and calculate an offset here and call offsetContent function.
React.useEffect(() => {
    const offset = width * index;

    offsetContent(offset);
}, [index]);

在第一次超时时,您更新了索引并认为它是 1 但实际上,当您计算偏移量时它又是 0,这就是滚动没有改变的原因。