[英]Problem in sync carrousel images with scrollview in React native
I have many problems using this implementation to sync the text and a carrousel images with scrollview in React Native.在 React Native 中使用此实现将文本和轮播图像与滚动视图同步时,我遇到了很多问题。 I try many options to fix this like setTimeout and contentOffset.
我尝试了很多选项来解决这个问题,比如 setTimeout 和 contentOffset。
The problem is the first render not call the scrollTo and this unsynchronize the text and image showed.问题是第一次渲染没有调用 scrollTo 并且这不同步显示的文本和图像。
I found this issue in React Native https://github.com/facebook/react-native/issues/6849 , but i can't extract a solution in this.我在 React Native https://github.com/facebook/react-native/issues/6849中发现了这个问题,但我无法从中提取解决方案。 Someone can help me?
有人可以帮助我吗?
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>
);
}
Look!!看!!
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]);
At the first timeOut, you updated index and thought it was 1 but actually, it was 0 again when you calculated an offset that's why the scroll didn't change.在第一次输出时,您更新了索引并认为它是 1,但实际上,当您计算偏移量时它又是 0,这就是滚动没有改变的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.