9-4 轮播图

393 阅读2分钟

在本节中,我们将使用 react-native-snap-carousel 库实现轮播图功能。该库功能丰富,定制性强,可以根据官方文档配置出所需的样式。

一、安装依赖

yarn add react-native-snap-carousel
yarn add @types/react-native-snap-carousel -D

二、创建轮播图组件

1. 文件结构调整

  • pages 文件夹下新建一个 Home 文件夹。
  • 将原有的 Home.tsx 移动到 Home 文件夹中,并重命名为 index.tsx
  • Home 文件夹中新建 Carousel.tsx,作为轮播图组件。

2. 实现轮播图组件

Carousel.tsx

import React from 'react';
import { View, StyleSheet, Dimensions, Platform } from 'react-native';
import Carousel, { Pagination, AdditionalParallaxProps } from 'react-native-snap-carousel';
import ParallaxImage from 'react-native-parallax-image';

interface CarouselProps {
  data: string[];
}

const data = [
  'http://img02.tooopen.com/images/20150525/tooopen_sy_126130985342.jpg',
  'http://file06.16sucai.com/2016/0507/3061924b603fe039dfd2508c2d49b897.jpg',
  'http://file06.16sucai.com/2016/0622/7e6078b0e83c032eae3394da78d9cea8.jpg',
  'http://file06.16sucai.com/2016/0330/b5f2887285d2fdef4e8cb92f525807e7.jpg',
  'http://file06.16sucai.com/2016/0624/c9aca6da153b011e4a075b7db2e59730.jpg',
  'http://file06.16sucai.com/2016/0726/656a4cc534888e6e74b3ce992a2af8f6.jpg',
];

const { width: viewportWidth, height: viewportHeight } = Dimensions.get('window');

// 获取宽度的百分比
function wp(percentage: number) {
  const value = (percentage * viewportWidth) / 100;
  return Math.round(value);
}

// 获取高度的百分比
function hp(percentage: number) {
  const value = (percentage * viewportHeight) / 100;
  return Math.round(value);
}

const slideHeight = hp(26); // 滑块的高度
const slideWidth = wp(90); // 滑块的宽度
const itemHorizontalMargin = wp(2); // 图片的左右外边距

const sliderWidth = viewportWidth; // 轮播图的宽度
const itemWidth = slideWidth + itemHorizontalMargin * 2; // 图片的宽度

const CarouselComponent: React.FC<CarouselProps> = ({ data }) => {
  const [activeSlide, setActiveSlide] = React.useState(0);

  const renderItem = ({ item }: { item: string }, parallaxProps: AdditionalParallaxProps) => {
    return (
      <View style={styles.slideInnerContainer}>
        <ParallaxImage
          source={{ uri: item }}
          containerStyle={styles.imageContainer}
          style={styles.image}
          parallaxFactor={0.35}
          showSpinner
          spinnerColor="rgba(0, 0, 0, 0.25)"
          {...parallaxProps}
        />
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <Carousel
        data={data}
        renderItem={renderItem}
        sliderWidth={sliderWidth}
        itemWidth={itemWidth}
        hasParallaxImages
        loop
        autoPlay
        onSnapToItem={(index) => setActiveSlide(index)}
      />
      <Pagination
        dotsLength={data.length}
        activeDotIndex={activeSlide}
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0, 0.35)',
          position: 'absolute',
          paddingHorizontal: 3,
          paddingVertical: 4,
          borderRadius: 6,
          top: -20,
        }}
        dotContainerStyle={{
          marginHorizontal: 6,
        }}
        dotStyle={{
          width: 6,
          height: 6,
          borderRadius: 3,
          backgroundColor: 'rgba(255, 255, 255, 0.92)',
        }}
        inactiveDotOpacity={0.4}
        inactiveDotScale={0.8}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: sliderWidth,
    height: slideHeight,
  },
  slideInnerContainer: {
    width: itemWidth,
    height: slideHeight,
    borderRadius: 8,
  },
  imageContainer: {
    flex: 1,
    marginBottom: Platform.select({ ios: 0, android: 1 }), // 防止 Android 渲染问题
    backgroundColor: 'white',
    borderRadius: 8,
  },
  image: {
    ...StyleSheet.absoluteFillObject,
    resizeMode: 'cover',
  },
});

export default CarouselComponent;

三、使用轮播图组件

Home/index.tsx 中引入并使用轮播图组件:

import React from 'react';
import { View } from 'react-native';
import Carousel from './Carousel';

const Home = () => {
  return (
    <View style={{ flex: 1 }}>
      <Carousel data={data} />
      {/* 其他组件 */}
    </View>
  );
};

export default Home;

四、注意事项

  1. 图片链接有效性:确保提供的图片链接是有效的。如果链接无法访问,可能是由于链接本身的问题或网络问题。请检查链接的合法性并适当重试。
  2. 分页指示器样式:通过 Pagination 组件的属性可以自定义分页指示器的样式。
  3. 自动轮播:通过设置 autoPlay 属性启用自动轮播功能。
  4. 无限轮播:通过设置 loop 属性启用无限轮播功能。

五、总结

在本节中,我们学习了如何使用 react-native-snap-carousel 实现轮播图功能,并对其进行了样式定制。下一节,我们将学习如何从后台获取数据,替换当前写死的数据。


注意:如果图片链接无法访问,请检查链接的合法性或更换图片资源。