我对 React Native 有点陌生,我正在尝试使用 Flatlist 创建一个卡片列表,我想为每张卡片显示几个图像作为轮播,我正在尝试使用 react-native-snap-carousel ,问题是当我滚动一张卡片时,所有卡片的索引都会移动。
如何为每张卡获取单独的索引?
import React, { useState, useRef } from 'react';
import { View, Text, Dimensions } from 'react-native';
import Carousel, { Pagination } from 'react-native-snap-carousel';
const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
const myCarousel = () => {
const [activeSlide, setActiveSlide] = useState(0);
const carousel = useRef();
const entries = [
{
title: 'card1',
},
{
title: 'card2',
},
{
title: 'card3',
},
{
title: 'card4',
},
];
var slides = [];
const entriesSplitter = () => {
let size = 1; //Based on the size you want
while (entries.length > 0) {
slides.push(entries.splice(0, size));
}
};
// render every single slide
const _renderItem = ({ item, index }) => {
return (
<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
{item.map(item => {
return <Text key={index}>{item.title}</Text>;
})}
</View>
);
};
return (
<View>
{entriesSplitter()}
<Carousel
ref={carousel}
data={slides}
renderItem={_renderItem}
onSnapToItem={index => setActiveSlide(index)}
sliderWidth={screenWidth}
sliderHeight={screenHeight}
itemWidth={screenWidth}
/>
<Pagination
dotsLength={4} // also based on number of sildes you want
activeDotIndex={activeSlide}
containerStyle={{ backgroundColor: 'red', borderWidth: 2 }}
dotStyle={{
width: 10,
height: 10,
borderRadius: 5,
marginHorizontal: 8,
backgroundColor: 'black',
}}
inactiveDotStyle={{
backgroundColor: 'pink',
}}
inactiveDotOpacity={0.4}
inactiveDotScale={0.6}
/>
<Carousel
ref={carousel}
data={slides}
renderItem={_renderItem}
onSnapToItem={index => setActiveSlide(index)}
sliderWidth={screenWidth}
sliderHeight={screenHeight}
itemWidth={screenWidth}
/>
<Pagination
dotsLength={4} // also based on number of sildes you want
activeDotIndex={activeSlide}
containerStyle={{ backgroundColor: 'red', borderWidth: 2 }}
dotStyle={{
width: 10,
height: 10,
borderRadius: 5,
marginHorizontal: 8,
backgroundColor: 'black',
}}
inactiveDotStyle={{
backgroundColor: 'pink',
}}
inactiveDotOpacity={0.4}
inactiveDotScale={0.6}
/>
</View>
);
};
export default myCarousel;
索引有一种圆圈样式,当你转到下一个时,会改变颜色以指示还剩多少,它们都同时移动