在 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,这就是滚动没有改变的原因。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章