HomeCarousel.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import React, {useState} from 'react';
  2. import {Image, StyleSheet, TouchableOpacity, View} from 'react-native';
  3. import Carousel from 'react-native-reanimated-carousel';
  4. const CAROUSEL_ASPECT_RATIO = 350 / 80; // 轮播图宽高比
  5. const INDEX_BACKGROUND_CURRENT = '#FFFFFF';
  6. const INDEX_BACKGROUND = 'rgba(255, 255, 255, 0.6)';
  7. type Props = {
  8. width: number; // 轮播图宽度
  9. data: {imgUrl: string}[]; // 数据的数组
  10. onPress?: (index: number) => void; // 点击事件
  11. };
  12. /**
  13. * @description: 首页轮播图
  14. */
  15. export default function HomeCarousel(props: Props) {
  16. const [currentIndex, setCurrentIndex] = useState(0);
  17. return (
  18. <View>
  19. <Carousel
  20. style={styles.carousel}
  21. loop
  22. width={props.width}
  23. height={props.width / CAROUSEL_ASPECT_RATIO}
  24. autoPlay={true}
  25. data={props.data}
  26. scrollAnimationDuration={3000}
  27. onScrollEnd={index => {
  28. setCurrentIndex(index);
  29. }}
  30. renderItem={({index}) => {
  31. return (
  32. <TouchableOpacity
  33. onPress={() => {
  34. props.onPress && props.onPress(index);
  35. }}>
  36. <Image
  37. style={{
  38. width: props.width,
  39. height: props.width / CAROUSEL_ASPECT_RATIO,
  40. }}
  41. source={{uri: props.data[index].imgUrl}}
  42. />
  43. </TouchableOpacity>
  44. );
  45. }}
  46. />
  47. <View style={styles.indexView}>
  48. <View style={styles.indexContent}>
  49. {props.data.map((_item, index) => {
  50. return (
  51. <View
  52. key={index}
  53. style={[
  54. styles.indexItem,
  55. {
  56. backgroundColor:
  57. currentIndex === index
  58. ? INDEX_BACKGROUND_CURRENT
  59. : INDEX_BACKGROUND,
  60. },
  61. ]}
  62. />
  63. );
  64. })}
  65. </View>
  66. </View>
  67. </View>
  68. );
  69. }
  70. const styles = StyleSheet.create({
  71. carousel: {
  72. borderRadius: 10,
  73. backgroundColor: '#FFFFFF',
  74. },
  75. indexView: {
  76. position: 'absolute',
  77. bottom: 0,
  78. left: 0,
  79. right: 0,
  80. height: 7.5,
  81. },
  82. indexContent: {
  83. flex: 1,
  84. flexDirection: 'row',
  85. justifyContent: 'center',
  86. },
  87. indexItem: {
  88. flexShrink: 1,
  89. width: 7.5,
  90. height: 2.5,
  91. marginHorizontal: 1.5,
  92. borderRadius: 2,
  93. },
  94. });